【问题标题】:Access template reference variables from component class从组件类访问模板引用变量
【发布时间】:2017-01-30 14:12:17
【问题描述】:
<div>
   <input #ipt type="text"/>
</div>

是否可以从组件类中访问模板访问变量?

也就是说,我可以在这里访问它吗,

class XComponent{
   somefunction(){
       //Can I access #ipt here?
   }
}

【问题讨论】:

    标签: angular typescript angular2-template


    【解决方案1】:
    @ViewChild('modal reference variable', { static: true }) name: ElementRef;
    

    有时它不适用于模态。所以当我在 Angular 中使用模态时会出错,所以我使用它。

    @ViewChild('modal reference variable', { static: true }) name!: ElementRef;
    

    如果您希望在不单击按钮的情况下执行模式,它肯定会起作用。

    【讨论】:

      【解决方案2】:

      这是@ViewChild 的一个用例:

      https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html

      class XComponent {
         @ViewChild('ipt', { static: true }) input: ElementRef;
      
         ngAfterViewInit() {
            // this.input is NOW valid !!
         }
      
         somefunction() {
             this.input.nativeElement......
         }
      }
      

      这是一个工作演示:

      https://stackblitz.com/edit/angular-viewchilddemo?file=src%2Fapp%2Fapp.component.ts

      【讨论】:

      • 但在调试时我得到 this.input 本身为未定义。
      • 正如我所提到的,它仅在事件ngAfterViewInit() 被触发后可用。你必须从 '@angular/core` 导入ViewChild ..
      • 但是我们如何设置一个值呢?我试过this.ipt.nativeElement.setAttribute('value', 'xxx'); 但没有任何反应。并且没有像 value()setValue() 这样的方法,即使我声明它的类型为 HTMLInputElement(我基于 IDE 的代码提示/自动完成)。就我而言,我不在乎阅读价值。我只需要设置不同的值。
      • 目前在假期.. 你也试过setProperty 吗?
      • 不应该this.input.nativeElement.value = 'test' 工作吗?!也许表单及其绑定存在特殊行为。
      猜你喜欢
      • 2017-11-04
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      • 2017-01-12
      • 2011-08-29
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      相关资源
      最近更新 更多