问题 'ElementRef'类型中不存在属性'value'


我试图设置值 #name1 如下图所示。但它显示编译时错误,如下所示。你能告诉我如何设置值 text 零件?在这里,我使用单向数据绑定和模板驱动方法。

[ts]'ElementRef'类型中不存在属性'value'。

html的

<ion-input type="text" name="{{question?.name}}" #name1="ngModel" ngModel> </ion-input>

.TS

  @ViewChild('name1') name1: ElementRef;

  constructor(){

   }

 getAnswer(){
     this.name1.value = 'Hello';//here it shows the above error
  }

2270
2018-05-08 09:33


起源

这是ElementRef的文档: angular.io/docs/ts/latest/api/core/index/ElementRef-class.html。但是你忽略了ngModel的全部意义,它可以在视图和组件状态之间进行双向绑定。 - JB Nizet
@ Mr.Sampath ......我正面临类似的错误..请问你看看这个链接....stackoverflow.com/questions/49044826/... - Heena
@ Mr.Sampath ......我正面临类似的错误..请问你看看这个链接....stackoverflow.com/questions/49044826/... - Heena


答案:


使用组件类型而不是模板变量

@ViewChild(TextInput) name1: TextInput;

这也可能有效(我不知道Ionic)。它可以使用本机HTML输入元素,但如果它是Angular组件,则上面是首选方法。

this.name1.nativeElement.value = 'Hello';

9
2018-05-08 09:36



这不起作用 this.name1.nativeElement.value = 'Hello';但是第一个正在工作。请你分享一篇关于这个概念的好文章吗?非常感谢 :) - Sampath
我真的没想到第二个例子可以工作。它可以使用本机HTML输入元素。 stackoverflow.com/questions/32693061/... 可能有帮助 - Günter Zöchbauer