【问题标题】:Template reference variable inside component组件内的模板引用变量
【发布时间】:2019-08-26 05:54:54
【问题描述】:

我有一个组件在其模板中声明了一些模板引用变量:

<div>
  <input #inp type="text">
  ...more stuff... 
</div>

如何从主组件(如表单)访问此“#inp”模板变量?

在我的例子中,我需要在打开表单时将焦点设置在这个输入上。

更新

我在“app-myform”表单中使用“app-mycomponent”,如下所示:

<form>
   <app-mycomponent></app-mycomponent>
   ...other components in this form
</form>

在 myform.component.ts 中,我想关注“app-mycomponent”中的“#inp”。

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以通过ViewChild 简单地访问模板变量。

    在您的组件中:

    @ViewChild('inp') // use the name of your template variable
    input: ElementRef;
    

    现在您可以访问输入,但它在ngAfterView 生命周期挂钩及更高版本中可用(请参阅here

    更新:要将此元素设置为焦点,您可以执行以下操作:

    this.input.nativeElement.focus()
    

    更新 2:有多种方法可以做到这一点。一种方法是通过EventEmitterSubject 通知您的子组件以将焦点设置到您的输入字段。另一种方法是通过ViewChild 访问子组件并执行一个函数,将焦点设置到您的输入字段。

    1.选项:

    myform.component.ts

    focus$: Subject<void> = new Subject();
    
    ...
    
    buttonClickFunction() {
        this.focus$.next();
    }
    

    myform.component.html

    <form>
        <app-mycomponent [focus$]="focus$"></app-mycomponent>
        ...other components in this form
    </form>
    

    app-mycomponent.component.ts

    @ViewChild('inp') // use the name of your template variable
    input: ElementRef;
    
    @Input()
    focus$: Subject<void>;
    
    ngAfterViewInit() {
        this.focus$.subscribe(() => {
            this.setFocusToInput();
        });
    }
    
    setFocusToInput() {
        this.input.nativeElement.focus()
    }
    

    2。选项:

    myform.component.ts

    @ViewChild(AppMyComponent) // your component class name
    appMyComponent: AppMyComponent
    
    ...
    
    // In a function or somewhere else you can call the function to set the focus
    buttonClickFunction() {
        this.appMyComponent.setFocusToInput();
    }
    

    app-mycomponent.component.ts

    @ViewChild('inp') // use the name of your template variable
    input: ElementRef;
    
    ...
    
    setFocusToInput() {
        this.input.nativeElement.focus()
    }
    

    目前,在你目前的情况下,我会向你推荐第二种选择。

    【讨论】:

    • 我可以在表单组件中这样做吗?
    • 你到底是什么意思?当然你可以从你的 component.ts 访问它
    【解决方案2】:

    您需要定义ViewChild。像这样:

    @ViewChild('inp')
    input: ElementRef<HTMLInputElement>;
    

    阅读更多: https://angular.io/api/core/ViewChild

    【讨论】:

      猜你喜欢
      • 2017-01-30
      • 2019-03-12
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      • 2017-04-27
      相关资源
      最近更新 更多