我使用下面的代码在父组件的按钮单击期间访问父组件中的子组件 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
但我无法在 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
关于angular - 如何在 angular2 中访问父组件中的子组件 HTML 元素值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45742655/