Soy nuevo en Angular. Intento alternar el párrafo usando un método. Declaré dos variables que contienen mi objeto para el estilo de mi párrafo. mi problema es que tengo un error
Error: src/app/directives-sample/directives-sample.component.html:6:7 - error TS2322: Type 'string' is not assignable to type '{ [klass: string]: any; }'. Type 'string' is not assignable to type '{ [klass: string]: any; }'. 6 <div [ngStyle]="!isSpecial ? 'currentStyles' : ''"> ~~~~~~~ src/app/directives-sample/directives-sample.component.ts:5:16 5 templateUrl: './directives-sample.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component DirectivesSampleComponent. ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** × Failed to compile.Aquí está mi código:
//html
<div [ngStyle]="isSpecial ? 'currentStyles' : 'specialStyles'"> This div is initially italic, normal weight, and extra large (24px). </div>//t
export class DirectivesSampleComponent implements OnInit { isSpecial: boolean = false; currentStyles = { 'font-style':'italic','font-weight': 'bold', 'font-size': '24px', 'color': 'red'}; specialStyles = { 'font-style':'italic','font-weight': 'italic', 'font-size': '16px', 'color': 'blue'}; constructor() { } ngOnInit(): void { } toggleSpecial() { this.isSpecial = !this.isSpecial; }¿Como puedó resolver esté problema?
La forma en que proporciona valor a [ngStyle] es incorrecta.
Comprobar: documento angular para NgStyle
La forma correcta podría ser proporcionar estilos especiales y estilos actuales tal como están y no como una cadena:
[ngStyle]="!isSpecial ? currentStyles : specialStyles"Le sugiero que use ngClass en lugar de ngStyle y puede comenzar creando sus 2 clases de estilo como se muestra a continuación:
.currentStyles { font-weight: bold; font-style: italic; font-size: 24px; color: red } .specialStyles { font-weight: italic; font-style: italic; font-size: 16px; color: blue }Luego, en su párrafo, puede tener lo siguiente:
<div [ngClass]="isSpecial ? 'specialStyles' : 'currentStyles'"> This div is initially italic, normal weight, and extra large (24px). </div>