简体   繁体   English

将Angular4中的[ngStyle]绑定到ngModel或2种方式绑定

[英]Binding [ngStyle] in Angular4 to ngModel or 2 way binding

I am trying to make one input box and add color to it. 我正在尝试制作一个输入框并为其添加颜色。 Same color should be added to the background of a paragraph. 相同的颜色应添加到段落的背景。 I am trying but getting error. 我正在尝试但出现错误。 Can someone help out? 有人可以帮忙吗?

home.html home.html

<input type="text" [(ngModel)]="colorName"/>
<p [ngStyle]="{background-color:'colorName'}">This is a paragraph.</p>

home.ts home.ts

  colorName: string = 'red';

Note: I want to do this with [ngStyle] and 2-way binding only in Angular4 注意:我只想在Angular4中使用[ngStyle]和2向绑定来执行此操作

Just remove quotos from colorName and add quotos in css property like this - 只需从colorName删除quotos,然后在css属性中添加quotos,如下所示:

<input type="text" [(ngModel)]="colorName"/>
<p [ngStyle]="{'background-color':colorName}">This is a paragraph.</p>

Working Example 工作实例

像这样做:

<p [ngStyle]="{'background-color':colorName}">This is a paragraph.</p>

You can add '' in background-color 您可以在background-color添加''

<input type="text" [(ngModel)]="colorName"/>
<p [ngStyle]="{'background-color':colorName}">This is a paragraph.</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM