简体   繁体   中英

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

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

home.ts

  colorName: string = 'red';

Note: I want to do this with [ngStyle] and 2-way binding only in Angular4

Just remove quotos from colorName and add quotos in css property like this -

<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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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