lys*_*030 1 javascript angularjs typescript angular
我想修改组件实例的字段。例如,在 test.component.ts 中:
@Component({
selector: 'test',
})
export class TestComponent {
@Input() temp;
temp2;
constructor(arg) {
this.temp = arg;
this.temp2 = arg * 2;
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用构造函数设置 temp 和 temp2 的值。我知道一种方法是通过执行以下操作来使用输入属性:
<test [temp]='1'></test>
Run Code Online (Sandbox Code Playgroud)
然而,这是在构建时间之后完成的,temp2不会相应地改变。如何从消费者的角度提供组件构造函数参数,以便在构造时设置“temp”和“temp2”的值?
谢谢!
事实上,由于组件生命周期的原因,组件的输入只能通过 ngOnInit 方法获得:
@Component({
selector: 'test',
})
export class TestComponent {
@Input() temp;
ngOnInit() {
console.log(this.temp);
}
}
Run Code Online (Sandbox Code Playgroud)
此外,我们只能在组件构造函数中使用通过依赖注入提供的参数。
因此,您不能使用 temp 属性的构造函数,因为组件生命周期。关于它取决于您如何提供它。如果是通过依赖注入,它会起作用,但你需要使用 @Inject 装饰器来指定注入什么。
您还可以查看此问题以了解更多详细信息:
| 归档时间: |
|
| 查看次数: |
8094 次 |
| 最近记录: |