组件内部的模板引用变量

时间:2019-04-04 12:56:06

标签: angular

我有一个组件,该组件的模板中声明了一些模板引用变量:

<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”。

2 个答案:

答案 0 :(得分:1)

您只需通过0.0 0.4 7.0 0.0 0.42 10.0 35.0 0.0 0.2 9.0 0.0 0.24 10.0 15.0 0.0 0.0 7.0 0.0 95.0 0.0 0.74 9.5 3.0 0.0 26.0 0.0 0.04 8.8 0.0 0.0 49.0 0.0 0.22 7.9 2.0 0.0 66.0 访问模板变量即可。

在您的组件中:

ViewChild

现在您可以访问输入,但是它在@ViewChild('inp') // use the name of your template variable input: ElementRef; 生命周期挂钩和更高版本中可用(请参见here

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

ngAfterView

更新2:有多种方法可以执行此操作。一种方法是通过this.input.nativeElement.focus() EventEmitter通知您的子组件,以将焦点设置到您的输入字段。另一种方法是通过Subject访问子组件并执行一个函数,该函数将焦点设置到您的输入字段。

1。选项:

myform.component.ts

ViewChild

myform.component.html

focus$: Subject<void> = new Subject();

...

buttonClickFunction() {
    this.focus$.next();
}

app-mycomponent.component.ts

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

2。选项:

myform.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()
}

app-mycomponent.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();
}

目前,在您当前的情况下,我建议您选择第二个选项。

答案 1 :(得分:0)

您需要定义ViewChild。像这样:

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

了解更多: https://angular.io/api/core/ViewChild