【问题标题】:Typescript assigning variable in ngAfterViewInit not workingngAfterViewInit中的打字稿分配变量不起作用
【发布时间】:2017-10-03 17:11:11
【问题描述】:

我正在尝试在 Angular 4 中创建一个组件,但遇到了一个我似乎无法解决的非常奇怪的问题。

我有一个简单的boolean,我试图根据@Input 进行设置

@Input('type') inputType: string = 'text';
showTextInput: boolean = false;
...
 ngAfterViewInit() {
    console.log('input', this.inputType);
    this.showTextInput = this.inputType === 'text' ? true : false;
    console.log('after condition', this.showTextInput);
}

这个组件的html是

<ts-input-item formControlName="name" 
               [control]="programForm.controls.name" 
               [label]="'Name'" 
               (onUpdateClicked)="updateItem($event,'Name','name')"> 
</ts-input-item>

所以在它当前的形式中,它应该默认输入text,它有点像,这让我很困惑。下面是console.log 的照片。

所以现在this.showTextInput 等于true。但是,如果我然后像这样在组件中使用它

  <ion-input #input 
             [type]="inputType" 
             [disabled]="isSelect"
             (keyup)="itemValueChanged(input.value)" 
             (keyup.enter)="itemUpdate()"
             *ngIf="showTextInput">
  </ion-input>

然后组件完全中断。主要是因为它没有显示为父组件不处理正在传递的表单名称,但简单地说,如果我什至添加类似

<div *ngIf="showTextInput"> foobar </div>

foobar 文本将不会显示并且没有错误。我是否在正确的生命周期挂钩中处理通行证?

【问题讨论】:

  • 浏览器控制台是否出现错误?
  • 不,不是简单的例子,对于ion-input 上的*ngIf,这是一个反应表单问题,表明name 表单元素不可用

标签: angular components angular2-components


【解决方案1】:

显式调用变更检测可能会有所帮助:

constructor(private cdRef:ChangeDetectorRef) {}

ngAfterViewInit() {
    console.log('input', this.inputType);
    this.showTextInput = this.inputType === 'text' ? true : false;
    console.log('after condition', this.showTextInput);
    this.cdRef.detectChanges();
}

【讨论】:

  • 谢谢 .. 我实际上无法弄清楚如何获得ChangeDetectorRef,但是当我搜索时,我看到我可以实现OnChanges 我不确定这有什么不同,但我会更深入地研究。干杯。
  • 更新ngOnChanges中的模型通常还需要cdRef.detectChanges()。 “热到ChangeDetectorRef”是什么意思?只需从@angular/core 导入即可。
  • 是的,我和ChangeDetectorRef一起工作了,不知道我之前做错了什么
  • 感谢您的反馈。很高兴听到你能成功。
  • 非常感谢,头撞墙半天后,我在解决方案中使用了这个:)
猜你喜欢
  • 2020-05-22
  • 2021-06-22
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多