父对子组件中的角度绑定函数

时间:2018-01-30 16:48:08

标签: angular binding components angular2-template

我有一个自定义输入字段作为子组件。我想将一个函数传递给子组件,这个函数将修改子组件的值。问题是需要在父组件中声明此函数。 (这样子组件是通用的)

我的 app.component.ts

import { Component } from '@angular/core';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.scss']
})
export class AppComponent {
 title = 'app';

 capitalize(){
  console.log("capitalized called");
  // here i want to .toUpperCase() the child component's data
  // in this case, the text entered in the input-text component
 }
}

app.component.html

<app-input-text label="label from parent" required="true [onKeyUp]="capitalize" error-msg="Required">
</app-input-text>

输入text.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
 selector: 'app-input-text',
 templateUrl: './input-text.component.html',
 styleUrls: ['./input-text.component.scss']
})
export class InputTextComponent implements OnInit {
 @Input('label') label: string;
 @Input('required') required: string;
 @Input('error-msg') errorMsg: string;
 @Input() onKeyUp: Function;

 constructor() {
 }
 ngOnInit(){
 }

输入text.component.html

<div>
 <label> {{label}} </label>
</div>

<div>
 <input [(ngModel)]=inputData
  type="text"
  name="inputText"
  id="inputText"
  #inputText="ngModel"
  required="{{required}}"
  (keyup)="onKeyUp()"
 />

 <p *ngIf="inputText.errors && inputText.errors.required" class="display-message">
  {{errorMsg}}
 </p>

</div>

2 个答案:

答案 0 :(得分:1)

<app-input-text label="label from parent" required="true 
  (onKeyUp)="capitalize($event)" error-msg="Required">
</app-input-text>


export class InputTextComponent implements OnInit { 
  @Input('label') label: string;
  @Input('required') required: string;
  @Input('error-msg') errorMsg: string;
  @Output()
  onKeyUp: EventEmitter<any> = new EventEmitter<any>();

  constructor() {
  } 

  ngOnInit(){
  }

  onKeyUpClient() {
    this.onKeyUp.emit(true);
  }
}


<input [(ngModel)]=inputData type="text" name="inputText" 
   id="inputText"
   #inputText="ngModel"
   required="{{required}}"
   (keyup)="onKeyUpClient()" />

答案 1 :(得分:0)

我不知道这是多么好的想法,但您可以使用ViewChild来访问子组件变量。使用@Input,您需要绑定this以保持this的正确范围。

省略了一些代码:

<app-input-text [KeyUp]="capitalize.bind(this)"></app-input-text>

TS

// import your child component and...
import { ViewChild } from '@angular/core';

// ...

@ViewChild(InputTextComponent) inputTextComponent: InputTextComponent

capitalize(){
  // here i want to .toUpperCase() the child component's data
  // in this case, the text entered in the input-text component
  this.inputTextComponent.inputData = 
       this.inputTextComponent.inputData.toUpperCase();;

}

和子组件:

inputData = '';
@Input() KeyUp: Function;

和你有相同的模板......

这是一个DEMO,其中包含默认StackBlitz模板中的一些不同的组件名称:) https://stackblitz.com/edit/angular-xgfsk6?file=app%2Fapp.component.html