我来自 Python 背景,但我开始尝试学习 Angular,但我真的遇到了麻烦。在组件之间工作让我感到困惑,我无法弄清楚。我举了一个很好的例子,我认为如果有人帮助我,它会帮助我理解 Angular。
我只有两个组件:一个“header”组件和一个 app 组件。在标头组件中,我要求输入用户名,然后他们单击一个按钮,然后它应该在下一个组件中显示“Hello {{name}}”。至少可以说我无法让它工作,这真的很令人沮丧。 Header 部分似乎工作正常,但它根本不与其他组件通信。按钮部分或“名称”部分都不起作用,所以我显然误解了在从父组件监听时我需要做的事情。
这是我的标题 HTML:
Name: <input type="text" id="userInput" value="Joe">
<button (click)=showName()>Show More</button>
这是我的标题 TS:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
bodyDiv = false;
inputName = '';
@Output() buttonClicked = new EventEmitter();
constructor() { }
ngOnInit() {
}
showName() {
console.log('showName clicked.');
this.bodyDiv = true;
this.inputName = document.getElementById('userInput').value;
console.log(this.inputName);
console.log(this.bodyDiv);
this.buttonClicked.emit(this.bodyDiv);
this.buttonClicked.emit(this.inputName);
}
}
这是主要组件的 HTML:
<app-header (buttonClicked)='showNextComponent($event)'></app-header>
<p *ngIf="![hiddenDiv]" [inputName]="name">Hello {{ name }} </p>
这是主要组件的 TS:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
hiddenComponent = true;
title = 'show-button';
showNextComponent() {
console.log('Button clicked.');
this.hiddenComponent = false;
console.log(this.hiddenComponent);
}
}
那么谁能告诉我我做错了什么并帮助我更好地理解 Angular 呢? :) 谢谢!
原文由 Emac 发布,翻译遵循 CC BY-SA 4.0 许可协议
用以下代码替换 showName 函数:
在您的主要组件中替换以下代码。
在您的 html 中替换以下代码:
如果您有任何问题,请告诉我,我建议尝试使用 ngmodel 或其他东西,而不是直接与 DOM 通信。