英文:
Programmatically update NGPrime Panel style property
问题
我对Angular还比较新,不确定我在TS或PrimeNG组件中是否做错了什么。
我有一个简单的响应式表单,我只是在提交时尝试更新一个样式属性。
我的面板组件从HTML中加载,包括自定义样式。
<p-panel header="No payment required.." [style]="{margin:'.5rem 2rem'}">
在组件的TS中,我使用ViewChild来获取它的引用。
@ViewChild(Panel, { static: false }) _Panel!: Panel;
我还尝试挂钩变更检测,但只是因为PrimeNG面板似乎没有更新?也许我不需要它?
@Component({
changeDetection: ChangeDetectionStrategy.Default
})
constructor(private cd: ChangeDetectorRef) { }
在按钮点击事件中,_Panel对象确实更新了,但UI没有更新?
this._Panel.style = { display: 'none' };
this.cd.detectChanges();
this.cd.markForCheck();
我做错了什么?
英文:
I'm fairly new to Angular and not sure if I'm doing something wrong in TS or with the PrimeNG component.
I have a simple reactive form and all I'm trying to do is update a style property when submitted.
My panel component loads from HTML including the custom style.
<p-panel header="No payment required.." [style]="{margin:'.5rem 2rem'}">
In the component TS I use ViewChild to get a handle on it.
@ViewChild(Panel, { static: false }) _Panel!: Panel;
I'm also trying to hook change detection BUT only because the PrimeNG panel doesn't seem to be updating? I may not need it?
@Component({
changeDetection: ChangeDetectionStrategy.Default
})
constructor(private cd: ChangeDetectorRef) { }
During a button click event the _Panel object does update but the UI does not?
this._Panel.style = { display: 'none' };
this.cd.detectChanges();
this.cd.markForCheck();
What am I doing wrong?
答案1
得分: 1
如果你只是想改变元素的可见性,我建议使用 *ngIf="..."
结构指令,并将其绑定到组件中的一个字段/属性上,根据需要将其设置为 true
或 false
,以控制其在 HTML 中的显示:
@Component({
...
// 你不需要指定 changeDetection: ChangeDetectionStrategry.Default
})
export class MyFormComponent {
...
panelVisible = true;
myMethodThatChangesPanelVisibility(...) {
this.panelVisible = false
}
}
<p-panel *ngIf="panelVisible" header="No payment required.." style="margin: .5rem 2rem;"></p-panel>
另外,请注意,由于 style
属性内的表达式不会改变,所以你不需要在 style
属性上使用 Angular 属性指令绑定。因此,我从你上面的代码中删除了方括号和花括号。
英文:
If you are just trying to change whether it is visible or not, I would use the *ngIf="..."
structural directive, and bind that to a field/property in your component that you can just set to true
or false
depending on when you want it to show up in your html
@Component({
...
// You don't need to specify changeDetection: ChangeDetectionStrategry.Default
})
export class MyFormComponent {
...
panelVisible = true;
myMethodThatChangesPanelVisibility(...) {
this.panelVisible = false
}
}
<p-panel *ngIf="panelVisible" header="No payment required.." style="margin: .5rem 2rem;">
Also, notice that you don't need to use Angular attribute directive binding on the style
attribute because the expression inside isn't going to change. So I removed the square brackets and curly brackets from what you had above.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论