对@output装饰器行为感到困惑

我正在通过输入输出装饰器,并尝试在以下示例中出于演示目的实现,以了解这些装饰器的重要性:

home.component.html

<app-login>
  <app-checkbox (checkBoxValue)="checkBoxValueChanged($event)"></app-checkbox>
</app-login>

login.comp.ts

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

@Component({
  selector: 'app-login',templateUrl: './login.component.html',styleUrls: ['./login.component.css']
})
export class LoginComponent{
  public checkBoxValueChanged(event){
    alert("called from here "+event)
  }
}

login.comp.html

<form>
    <input type="text" placeholder="email"/>
    <input type="password" placeholder="password"/>
    <ng-content></ng-content>
    <input type="button" value="login"/>
</form>

checkbox.comp.ts

import { Component,EventEmitter,Output } from '@angular/core';

@Component({
  selector: 'app-checkbox',templateUrl: './checkbox.component.html',styleUrls: ['./checkbox.component.css']
})
export class CheckboxComponent{
  @Output() checkBoxValue : EventEmitter<any> = new EventEmitter();
  valueChanged(value){
    this.checkBoxValue.emit(value)
  }
}

checkbox.comp.html

<input type="checkbox" value="Y" (change)="valueChanged($event.target.value)"/> Remember Me 

根据我的理解,checkBoxValueChanged应该位于登录组件中,因为复选框组件在登录组件内部被调用,但这不起作用。如果我在登录组件内部编写了checkBoxValueChanged,则会收到ERROR TypeError: _co.checkBoxValueChanged is not a function的错误消息。但是,当我在home组件内编写此函数时,一切正常,但我感到困惑,为什么在登录组件中它不起作用。

doctorzzr 回答:对@output装饰器行为感到困惑

checkBoxValueChanged中使用home.component.ts组件时,您应该在app-checkbox组件中拥有home.component.ts函数,只需将checkBoxValueChanged函数移至home.component.tslogin.comp.ts开始,您将收到发出的值,剩下的就是完美的!!

或者如果您想在login.comp.ts中发出值,请不要遵循上述要点,而应将<app-checkbox (checkBoxValue)="checkBoxValueChanged($event)"></app-checkbox>标签移动到login.comp.html ...

希望对您有帮助!! :)

本文链接:https://www.f2er.com/3144970.html

大家都在问