Bry*_*ner 70 typescript angular
编写Angular 2.0组件时,如何设置属性的默认值?
例如 - 我想foo
默认设置为'bar',但绑定可能会立即解析为'baz'.这在生命周期钩子中如何发挥作用?
@Component({
selector: 'foo-component'
})
export class FooComponent {
@Input()
foo: string = 'bar';
@Input()
zalgo: string;
ngOnChanges(changes){
console.log(this.foo);
console.log(changes.foo ? changes.foo.previousValue : undefined);
console.log(changes.foo ? changes.foo.currentValue : undefined);
}
}
Run Code Online (Sandbox Code Playgroud)
给定以下模板,这是我期望的值.我错了吗?
<foo-component [foo] = 'baz'></foo-component>
// Logged to console:
// 'baz'
// 'bar'
// 'baz'
<foo-component [zalgo] = 'released'></foo-component>
// Logged to console:
// 'bar'
// undefined
// undefined
Run Code Online (Sandbox Code Playgroud)
Mik*_*kki 101
这是一个有趣的主题.你可以玩两个生命周期钩子来弄清楚它是如何工作的:ngOnChanges
和ngOnInit
.
基本上,当您将默认值设置为Input
平均值时,仅在该组件没有值的情况下才会使用它.而有趣的部分将在组件初始化之前进行更改.
假设我们有这样的组件有两个生命周期钩子和一个属性来自input
.
@Component({
selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
@Input() property: string = 'default';
ngOnChanges(changes) {
console.log('Changed', changes.property.currentValue, changes.property.previousValue);
}
ngOnInit() {
console.log('Init', this.property);
}
}
Run Code Online (Sandbox Code Playgroud)
情况1
html中包含的组件没有定义的property
值
结果我们将在控制台中看到:
Init default
这意味着onChange
没有被触发.触发了Init,property
值default
与预期一致.
情况2
包含在具有setted属性的html中的组件 <cmp [property]="'new value'"></cmp>
结果我们将在控制台中看到:
Changed
new value
Object {}
Init
new value
这个很有意思.首先是触发了onChange
hook,它设置property
为new value
,而前一个值是空对象!只有在onInit
用新的值触发了钩子之后property
.
Par*_*per 13
这是最好的解决方案。(角度所有版本)
解决方案:为@Input 变量设置默认值。如果没有值传递给该输入变量,则它将采用默认值。
我已经为这种类似的问题提供了解决方案。您可以从这里找到完整的解决方案
export class CarComponent implements OnInit {
private _defaultCar: car = {
// default isCar is true
isCar: true,
// default wheels will be 4
wheels: 4
};
@Input() newCar: car = {};
constructor() {}
ngOnInit(): void {
// this will concate both the objects and the object declared later (ie.. ...this.newCar )
// will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT
this.newCar = { ...this._defaultCar, ...this.newCar };
// console.log(this.newCar);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
78010 次 |
最近记录: |