访问子元素

时间:2018-02-14 11:30:03

标签: angular angular5 viewchild

我认为这样做的唯一方法是提供服务,但我想知道是否有其他办法可以实现。

父:

<h1> Parent title </h1>
<child-element></childElement>

子:

<form #f="ngForm">
    <mat-card-content>
      <mat-input-container>
        <input matInput [(ngModel)]="id" name="id" placeholder="ID"  #input/>
      </mat-input-container>
      <mat-input-container>
        <input matInput [(ngModel)]="name" name="name" placeholder="NAME"  #input/>
      </mat-input-container>
    </mat-card-content>
</form>

来自孩子,我可以使用@ViewChildren访问:

export class ChildComponent implements OnInit {

    @ViewChildren('input') inputs;
   //rest of code
}

但是可以从父母那里访问所有这些吗?

1 个答案:

答案 0 :(得分:1)

不太清楚,但如果我明白了:

<h1> Parent title </h1>
<child-element #child></childElement>

在您的父母TS:

@ViewChild(ChildComponent) child: ChildComponent;

doSomething() {
  console.log(this.child.inputs);
}

这允许父级作为Javascript对象访问子级。这是你想要的吗?

相关问题