【问题标题】:Angular TemplateRef ExpressionChangedAfterItHasBeenCheckedErrorAngular TemplateRef ExpressionChangedAfterItHasBeenCheckedError
【发布时间】:2017-10-20 19:20:25
【问题描述】:

只是在玩 TemplateRef

所以我设置了这个简单的代码

在我的 chrome 控制台中

ERROR 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改

如果在 ng-template 里面我可以看到重点

将是本文中的 ngModel

Angular - Exception when adding dynamic component

但使用简单的绑定.....

@Component({
  selector: 'app-root',
  template: `
    <ng-template #myTemplate>
      <button class="tab-button"
                  (click)="login()">{{loginText}}</button>
      <button class="tab-button"
                  (click)="signUp()">{{signUpText}}</button>
    </ng-template>
  `
})
export class AppComponent  implements AfterViewInit, AfterContentInit {
  @ViewChild('myTemplate') tmpl: TemplateRef<any>;

  loginText = 'Login';
  signUpText = 'Sign Up';

  constructor(private view:ViewContainerRef){}

  login() {
    console.log('Login');
  }

  signUp() {
    console.log('Sign Up');
  }

  ngAfterViewInit(): void {
   this.view.createEmbeddedView(this.tmpl)
  }

  ngAfterContentInit(): void {
    // It doesn't work either
    //this.view.createEmbeddedView(this.tmpl);
  }
}

提前致谢

【问题讨论】:

  • 如果将 createEmbeddedView 调用放在 ngOnInit 中会怎样?这应该可行。

标签: angular


【解决方案1】:

由于#myTemplate 是静态视图查询,您可以使用ngOnInit 挂钩

ngOnInit(): void {
   this.view.createEmbeddedView(this.tmpl)
}

【讨论】:

  • 如果不是静态的怎么办?
  • @MattTreichel 您应该等到它初始化。例如。在ngAfterViewInit做吧
  • 但这就是导致ExpressionChangedAfterItHasBeenCheckedError...
  • @MattTreichel 尝试将其包装在 Promise 中,否则您将不得不显式调用更改检测
猜你喜欢
  • 2017-11-25
  • 2018-01-20
  • 2021-01-02
  • 2017-12-14
  • 1970-01-01
  • 2018-02-03
  • 2018-03-05
  • 2018-09-02
  • 2017-11-07
相关资源
最近更新 更多