gpt4 book ai didi

css - Angular2 CSS 样式/类字符串作为组件的输入

转载 作者:行者123 更新时间:2023-11-28 12:01:22 26 4
gpt4 key购买 nike

背景

我有一个包装两个 span 元素的组件。我希望父组件能够通过将 CSS 类和样式指定为输入(最好是简单字符串)来设置内部两个 span 的样式。这是我希望它看起来像的一个简化示例:

代码

应用组件(父级)

@Component({
selector: 'my-app',
template: `
<div>
<app-two-spans [classArg1]="'class1'" [classArg2]="'class2'"
[styleArg1]="'width: 100px'" [styleArg2]="'width:200px'"></app-two-spans>
</div>
`, style: `
::ng-deep .class1 {
border: 1px solid black;
}
::ng-deep .class2 {
border: 1px solid blue;
}
`
})
export class App {

}

两个跨度组件(子)

import {Component, Input, Output, EventEmitter} from '@angular/core';

@Component({
selector: 'app-two-spans',
template: `
<span *ngIf="flag" [ngClass]="classArg1" [ngStyle]="styleArg1"
(click)="flag = !flag">click me</span>
<span *ngIf="!flag" [ngClass]="classArg2" [ngStyle]="styleArg2"
(blur)="flag = !flag" contenteditable="true">
click me to change my value</span>
`
})
export class TwoSpansComponent {
flag: boolean = true;
@Input() styleArg1: string;
@Input() styleArg2: string;
@Input() classArg1: string;
@Input() classArg2: string;
constructor() {}
}

问题

类样式似乎适用于我的本地环境(尽管由于某种原因它似乎不适用于 Plunker)。但是,style 没有出现。我看过其他关于样式作为输入的帖子,但据我所知,这通常是通过传递样式值对 ( see accepted answer here ) 来完成的。但是,我真的很想将这些样式作为简单的字符串传递,以便更轻松地使用组件。我注意到控制台中出现以下错误:ERROR Error: Cannot find a differ supporting object 'width: 100px'。我完全不确定这意味着什么。

Plunker here

有没有办法做到这一点?我怎样才能让父组件具有样式化子组件的能力?

最佳答案

ngStyle 接受一个 Object 而不是纯字符串。您可以将您的样式传递为:

[styleArg1]="{ width: '100px' }"
[styleArg2]="{ width: '200px' }"

关于css - Angular2 CSS 样式/类字符串作为组件的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45661957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com