如何在父级的子组件上检测模糊事件

时间:2019-09-06 14:23:28

标签: angular typescript viewchild event-binding

我正在做一个有角度的项目,我在设置字段验证错误消息时遇到问题。我想在触摸组件且模型无效时设置错误类别。

我尝试将事件(模糊)放在子组件上,并将事件放在子组件的html内。

//InitGame.js
export default class InitGame {
    constructor(){
        this.avaliablePoints = 5;
        this.healthPoints = 10;
        this.dmgPoints = 10;
        this.stats = undefined;
}

removeHealthPoints() {
        if (this.healthPoints >= 11) {
            this.avaliablePoints += 1;
            this.healthPoints -= 1;
        }
        else {
            console.log("10 health points is minimum");
        }
        document.getElementById("healthPoints").innerHTML = "Health: " + this.healthPoints;
        document.getElementById("points").innerHTML = "Avaliable points: " + this.avaliablePoints;
}

addHealthPoints() {
        if (this.avaliablePoints == 0) {
            console.log("0 avaliablePoints");
        }
        else {
            this.avaliablePoints -= 1;
            this.healthPoints += 1;
        }
        document.getElementById("healthPoints").innerHTML = "Health: " + this.healthPoints;
        document.getElementById("points").innerHTML = "Avaliable points: " + this.avaliablePoints;
}
getAvaliablePoints() {
        return this.avaliablePoints;
}
getHealthPoints() {
        return this.healthPoints;
}
<!--parent-->
<form #formGlobal="ngForm>
<child-component (modelChange)="syncWithHiden()" ></child-component>
<input type="hidden" #data="ngModel">
</form>

我想在用户单击ng-select并将值保留为空时将隐藏的输入数据#data设置为脏或触摸

1 个答案:

答案 0 :(得分:3)

从父级处理子级中发生的事件的最简单方法是在子级中创建一个输出事件,该事件在您要处理的事件发生时发出,然后由父级处理。

基本上

child.ts

@Component({
  selector: 'child-component',
  template: `
    <form>
      <ng-select (blur)="internalEventHandler(data)">....</ng-select>
    </form>  
  `,
  styles: []
})

export class ChildComponent  {
  @Output() event = new EventEmitter();

  internalEventHandler = (dataToOutput: any) => this.event.emit(dataToOutput);
}

parent.ts

@Component({
  selector: 'parent-component',
  template: `
    <form #formGlobal="ngForm>
      <child-component (event)="handleChildEvent($event)"></child-component>
      <input type="hidden" #data="ngModel">
    </form>
  `,
  styles: []
})

export class ParentComponent  {
  handleChildEvent = (dataFromChild) => {
    //do stuff...
  }
}