【问题标题】:Angular 4: access template element in other componentAngular 4:访问其他组件中的模板元素
【发布时间】:2017-11-07 17:03:21
【问题描述】:

我正在使用 Angular 4。我试图在另一个组件中访问一个组件的模板元素。我发现唯一有效的东西(如下图所示)不是很“Angular”。

组件#1(包含模板):

  @Component({
    template: `...<input type="text" id="txtUserName" />`

组件#2(在点击事件中获取上述组件的模板元素值):

  (<HTMLInputElement>document.getElementById('txtUserName')).value;

我在 ElementRef、ViewChild 等上发现了无数的 sn-ps,但它们都不能真正用于获取模板元素的值。 有谁知道 Angular 4 方法可以完成我上面所做的相同事情?

【问题讨论】:

    标签: angular templates components


    【解决方案1】:

    组件#1 和组件#2 之间是否有任何关系。

    如果两者都有父子关系,您可以使用@ViewChild() 或@input 访问

    如果没有关系比尝试使用共享服务访问 更多信息https://angular.io/docs/ts/latest/cookbook/component-communication.html

    【讨论】:

    • 如此处所述...“Angular-y”方法是组件应该访问另一个组件的模板,除非组件之间存在特定关系。您可以改为使用此处建议的服务。我这里有一个例子:blogs.msmvps.com/deborahk/…
    • DeborahK,我没有足够的 StackOverflow 积分来支持你,但你的文章正是我所需要的。现在我可以通过 getter 在其他组件中检索模板元素的值。谢谢!
    【解决方案2】:

    您可以在 Angular 4 中使用 FormGroups 来做到这一点。

    组件 A

    FormGroups 允许您将表单元素定义为表单的特征,然后将该描述附加到表单。

    在组件 A 构造函数内部

     public constructor(build: FormBuilder) {
         this.form = build.group({
             username: build.control('')
         });
     }
    

    您现在可以在模板中使用该表单组。

    <form [formGroup]="form">
        <component-b></component-b>
    </form>
    

    如果您将子组件放在使用 FormGroup 的 &lt;form&gt; 中,则可以通过依赖注入访问控件。

    组件 B

    您可以像这样通过构造函数中的指令访问 FormGroup。

    public constructor(public formGroupDir: FormGroupDirective) {
    }
    

    您必须等到您的组件准备好访问用户名控件。

    public ngAfterContentInit(): void {
        let formGroup = this.formGroupDir.form;
        this.control = formGroup.get('username');
    }
    

    在子模板中,您现在可以将输入绑定到表单组控件。

    <input type="text" [formControl]="control"/>
    

    现在一切就绪。 A 组件将通过 FormGroup 事件从子组件接收表单更改通知。

    【讨论】:

    • 感谢 ThinkingMedia。 DeborahK 的回答(上图)完全符合我的需要。不过,我也会尝试一下您的解决方案,因为我想了解在组件之间共享数据的各种方式。
    【解决方案3】:

    最简单的工作示例是

    import { Component, OnInit, ViewChild, TemplateRef, Input  } from '@angular/core';
    
    @Component({
      selector: 'template-component',
      template: `
    <ng-template #templateX>
      <div>This is templateX with text: {{myText}}</div>
    </ng-template>  
      `
    })
    export class TemplateComponent {
      @ViewChild('templateX')
      templateXRef: TemplateRef<any>;
    
      @Input()
      myText: string;
    }
    
    
    @Component({
      selector: 'my-component',
      template: `
      <template-component #link myText="John Smith">
      </template-component>
    
      <div>Hello there.</div>
    
      <ng-container *ngTemplateOutlet="link.templateXRef"></ng-container>  
      `
    })
    export class MyComponent {
    }
    

    stackblitz 上查看更复杂的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-27
      • 2017-12-04
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多