我正在尝试在下面的'EditdialogComponent'中设置CSS类(这是模态视图(,具体取决于称为'appcomponent''''''showme'的输入属性:
- html代码:
<div [ngClass]="showMe? 'ui active modal': 'ui modal'">
<i class="close icon"></i>
<div class="header">
Edit
</div>
<div class="actions">
<div (click)="cancel()" class="ui black deny button">
Cancel
</div>
<div class="ui positive right labeled icon button">
OK
<i class="checkmark icon"></i>
</div>
</div>
</div>
2。打字稿代码:
import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
@Component({
selector: 'edit-dialog',
templateUrl: './edit-dialog.component.html',
styleUrls: ['./edit-dialog.component.css']
})
export class EditDialogComponent implements OnInit {
_showMe: boolean
@Input() subject: string
@Input() set showMe(value: boolean) {
this._showMe = value
window.alert('Trying to show modal')
}
get showMe() : boolean {
return this._showMe
}
cancel() {
this._showMe = false
}
constructor() { }
ngOnInit() {
}
}
以下是用于将" editdialogcomponent"包含在" appcomponent"中的代码:
- html代码:
<button (click)='edit()'>Edit</button>
<edit-dialog [showMe]="show_edit_modal" subject='foobar'></edit-dialog>
- 打字稿代码:
edit() {
window.alert('Trying to show modal')
this.show_edit_modal = true }
问题是在showMe
@input((从EditDialogComponent
中更改(通过单击模式的"取消"按钮调用(,它无法检测到数据绑定的更改(即Show_edit_modal(由AppComponent.edit()
调用(每当我单击AppComponent的编辑按钮时,都会显示"尝试显示模式"(,因为EditDialogComponent.ngOnChanges()
的警报停止显示。
为什么要从内部组件内更改@Input变量会导致其未能从外部组件中检测新更改?
@Input
只是一种一种绑定。如果您还要更改父组件中的值,则必须创建两个方法数据绑定。为此,您必须创建一个输出的输出,其输入(在您的情况下为showMe
( 更改(例如:showMeChange: EventEmitter<any>
(,并在Showme Setter中发射。
现在,您可以在您的父部件中使用它,例如ngModel
。
<edit-dialog [(showMe)]="show_edit_modal" subject='foobar'></edit-dialog>
我在这里创建了一个完整的示例:https://stackblitz.com/edit/angular-c83djz
这是按预期工作的。@Input()
不会引起更改。
showMe="{{show_edit_modal}}"
是Angulars改变检测检查。
ir更好
[showMe]="show_edit_modal"
实际通过布尔值而不是字符串
您可以做的是使showMe
成为Setter
_showMe:boolean;
@Input() set showMe(val: boolean) {
this._showMe = val;
window.alert('Trying to show modal')
}
get showMe() : boolean {
return this._showMe;
}