示例
app.component.html 模板如下:
<app-hello#instance[itsId]="'aaa_er3df3'"[itsTitle]="item?.title"[isDelete]="true"(ngModelChange)="onChange($event, item)"></app-hello>
app.component.ts 中获取到组件实例进行了额外属性赋值:
@ViewChild('instance') instance: AppHelloComponent;aa() {this.instance['value'] = '33333';}
app-hello.component.ts:
export class AppHelloComponent implements OnInit {_itsTitle = '';_value = '';constructor() {...}@Input() itsId = '';@Input()set itsTitle(title) {this._itsTitle = title}get itsTitle() {return this._itsTitle;}@Input() isDelete = false;@Input()set value(val) {if (this.isDelete) {return null;}this._value = val}get value() {return this._value;}ngOnInit() {...}}
执行顺序
- AppHelloComponent 的 constructor;
按照app.component.html中模板上书写的属性顺序,依次给 AppHelloComponent 赋值;
angular源码:core.js 中的 function updateProp(view, providerData, def, bindingIdx, value, changes) {}
调用 AppHelloComponent 的生命周期方法 ngOnInit;
- 给 AppHelloComponent 的属性 value 赋值。
在 value 的 setter 中调用了 this.isDelete 属性,如果 isDelete 不在模板中赋值,则此处未必能取得正确的值(true),而有可能取得 AppHelloComponent 的默认值(false)
