示例

app.component.html 模板如下:

  1. <app-hello
  2. #instance
  3. [itsId]="'aaa_er3df3'"
  4. [itsTitle]="item?.title"
  5. [isDelete]="true"
  6. (ngModelChange)="onChange($event, item)"
  7. >
  8. </app-hello>

app.component.ts 中获取到组件实例进行了额外属性赋值:

  1. @ViewChild('instance') instance: AppHelloComponent;
  2. aa() {
  3. this.instance['value'] = '33333';
  4. }

app-hello.component.ts:

  1. export class AppHelloComponent implements OnInit {
  2. _itsTitle = '';
  3. _value = '';
  4. constructor() {
  5. ...
  6. }
  7. @Input() itsId = '';
  8. @Input()
  9. set itsTitle(title) {
  10. this._itsTitle = title
  11. }
  12. get itsTitle() {
  13. return this._itsTitle;
  14. }
  15. @Input() isDelete = false;
  16. @Input()
  17. set value(val) {
  18. if (this.isDelete) {
  19. return null;
  20. }
  21. this._value = val
  22. }
  23. get value() {
  24. return this._value;
  25. }
  26. ngOnInit() {
  27. ...
  28. }
  29. }

执行顺序

  1. AppHelloComponent 的 constructor;
  2. 按照app.component.html中模板上书写的属性顺序,依次给 AppHelloComponent 赋值;

    angular源码:core.js 中的 function updateProp(view, providerData, def, bindingIdx, value, changes) {}

  3. 调用 AppHelloComponent 的生命周期方法 ngOnInit;

  4. 给 AppHelloComponent 的属性 value 赋值。

    在 value 的 setter 中调用了 this.isDelete 属性,如果 isDelete 不在模板中赋值,则此处未必能取得正确的值(true),而有可能取得 AppHelloComponent 的默认值(false)