gpt4 book ai didi

angular - 在 Angular 组件中声明变量。在 ngOnInit 中还是在变量声明中?

转载 作者:行者123 更新时间:2023-12-02 19:06:35 26 4
gpt4 key购买 nike

在 Angular 7 应用程序中,我有以下组件:

export class ListComponent implements OnInit {

visible: boolean;

ngOnInit() {
this.visible = false;
}

toggle() {
this.visible = !this.visible
}

}

我的观点是:

<table *ngIf="visible">
Table content
</table>

在ngOnInit中设置visible的初始值或在变量声明中设置有什么区别,例如:

visible: boolean = false;

哪种方法更好?

最佳答案

When you already knew the data you're assigning in a variable, it is best to initialize them upon declaration

@Component({...})
export class ChildComponent {

visible: boolean = false;

}

But if your variable is dependent to another service or function, then you need to specify it inside the ngOnInit not on the constructor

"Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".

"ngOnInit() is better place to "start" - it's where/when components' bindings are resolved."

-Pardeep Jain

@Component({...})
export class ChildComponent {

visible: boolean;

constructor(private sampleService: SampleService) {}

ngOnInit() {
this.visible = this.sampleService.isVisible; // May it a plain boolean or an Observable that you need to subscribe
}

}

关于angular - 在 Angular 组件中声明变量。在 ngOnInit 中还是在变量声明中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55044630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com