如何在 angular2 中访问父组件中的子组件 HTML 元素值?

2024-04-05

我使用下面的代码在父组件的按钮单击期间访问父组件中的子组件 HTML 元素值。

子组件.ts:-

@Component({
  selector: 'child-component',
  template: `<md-input-container><label>Title</label><input [(ngModel)]="Title" #Title></md-input-container><md-input-container><label>Name</label><input [(ngModel)]="name" #Name></md-input-container><md-input-container class="md-block" flex-gt-sm><label>State</label><md-select [(ngModel)]="user.state" #State><md-option *ngFor="let state in states" value="{{state.abbrev}}">{{state.abbrev}}</md-option></md-select></md-input-container>`
})

export class ChildComponent {
  // some code here
}

父组件.ts:-

import {
    Directive,
    EventEmitter,
    Output,
    OnInit,
    ElementRef
} from '@angular/core';

@Component({
  selector: 'parent-component',
  template: `<child-component></child-component><button class="md-button md-ink-ripple" type="submit" (click)="SaveCustomerDetails()"><span class="ng-scope">Submit</span></button>`
})

export class ParentComponent {
   @ViewChild('Title') title:ElementRef;
   @ViewChild('State') state:ElementRef;
   Title: string;
   State: string;
   SaveCustomerDetails() {
     this.Title = this.title.nativeElement.value; // undefined
     this.State= this.state.nativeElement.innerHTML; // undefined
   }
}

笨蛋:- https://plnkr.co/edit/r3237ta1XzhM2PX09pMl?p=preview https://plnkr.co/edit/r3237ta1XzhM2PX09pMl?p=preview

但我无法在 SaveCustomerDetails 函数中获取子组件的 HTML 元素值。如何使用ViewChild方法获取父组件中输入的值?


并不是说我在这里提倡使用 @ViewChild (它是一个紧密耦合的解决方案),但如果您想在不使用 @Output 属性的情况下做到这一点,这是可能的:

@Component({
  selector: 'child-component',
  template: `<input (change)='title=$event.target.value'>
             <input (change)='name=$event.target.value'>`
})

export class ChildComponent {
  title = "";
  name = "";
}

@Component({
  selector: 'parent-component',
  template: `<child-component #child></child-component><button type="submit" (click)="SaveCustomerDetails()">Submit</button>`,
})
export class ParentComponent {

  @ViewChild('child') myChild: ChildComponent;

  SaveCustomerDetails(){

    console.log(this.myChild.title + "" + this.myChild.name);
  }
}
}

我在这里修改了你的plunker:https://plnkr.co/edit/mCGcIW1AVX2e9gEBzeC0?p=preview https://plnkr.co/edit/mCGcIW1AVX2e9gEBzeC0?p=preview

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 angular2 中访问父组件中的子组件 HTML 元素值? 的相关文章

随机推荐