如何访问子元素标记ID

时间:2016-12-15 14:12:00

标签: angular typescript

我有以下设置:

<parent>
    <a (click)="getChildId(childId)">
    <child somethingRequired></child>
</parent>

子模板文件:

<template #childId></template>

您能否指导一下获取#childId并将其传递给getChildId函数的最佳方法。

由于

1 个答案:

答案 0 :(得分:0)

简单的答案是在 ViewChild ChildComponent 中使用 #localVariable API strong> ParentCompnent ,如下所示,

DEMO:https://plnkr.co/edit/V8srD4WnlowP8UACNIpI?p=preview

儿童

<input #childId>

export class child {
  @ViewChild('childId') childId:ElementRef;
}

<强>父

<a (click)="writeValue(has.childId)">GrabValue</a><br>
                       //<<===has variable has an ability to access variables and methods of child component
<child #has></child>                            
       //<<===has is a local variable which can access variables and methods of child component



export class AppComponent {
  source='images/angular.png';
  writeValue(value){
    console.log('parent writeValue');
    console.log(value.nativeElement.value);
  }
}