【发布时间】:2021-02-15 12:30:19
【问题描述】:
我正在学习 Angular。我已经阅读了documentation 和五篇博客文章,它像泥巴一样清晰。我认为有两个模板。子模板有一个按钮。当用户单击按钮时,我希望在父模板中显示一个元素(说明卡)。当用户再次单击按钮时,我希望元素不显示。即,子按钮打开和关闭父元素。
<button (click)="toggleInstructions()">Instructions</button>
在我的标题(子)组件中,我创建了一个输出事件发射器sendData、一个布尔变量showInstructions,以及一个在true 和false 之间切换showInstructions 的函数。在记录showInstructions(效果很好!)后,它会调用sendData 来发出数据。我创建了一个新变量myData,因为我对this 的使用感到困惑。
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent {
@Output() sendData = new EventEmitter<boolean>();
showInstructions: boolean = false;
toggleInstructions(myData: boolean) {
console.log("Clicked!");
switch (true) {
case (this.showInstructions === true):
this.showInstructions = false;
break;
case (this.showInstructions === false):
this.showInstructions = true;
break;
default:
console.log("Error in switch-case.");
}
console.log(this.showInstructions);
myData = this.showInstructions;
console.log(myData);
this.sendData.emit(myData);
}
}
在父组件中,我导入了子组件(HeaderComponent)并创建了一个函数toggledInstructions 来接收数据。当我单击该按钮时,没有任何记录。
import { Component } from '@angular/core';
import { HeaderComponent } from './header/header.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
toggledInstructions(myData: boolean) {
console.log("Data coming in!");
console.log(myData);
}
}
我很困惑这应该如何工作。除了数据变量名称(myData)之外,我在连接发送和接收功能的documentation 中什么都看不到。
感谢您的帮助!
【问题讨论】:
-
你能提供stackblitz吗?
-
请提供app.component.html
标签: angular