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

标签 angular typescript angular2-template

我使用下面的代码在父组件的按钮单击期间访问父组件中的子组件 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/

相关文章:

javascript - 无法在 ionic 2 中从 JS 切换到 TS

angular - 如何在 Angular 2+ 中将延迟加载的组件选择器包含到另一个组件的 HTML 中

html - Angular2 禁用按钮

javascript - 如何防止(单击)将该类添加到 ngFor 中的所有元素?

typescript - Observable 联合上的 take() 期望什么?

angular - 使用参数动态创建组件

angular - 如何使用 karma+jasmine 测试 Angular 2 中的位置

angular - Angular 输入[类型=数字]中的验证错误?

dependency-injection - 带有可选参数的 DI 构造函数

angular - 如何配置 Karma 以包含 angular-cli 项目的全局 scss 文件?