【问题标题】:I need to change the style of an element of my Array in Angular我需要在 Angular 中更改我的数组元素的样式
【发布时间】:2020-05-10 15:30:20
【问题描述】:

我需要在数组的第二个元素上设置 Style:"text-decoration: line-through",我该怎么做? 我尝试使用 CSS 和 [ngStyle] 但没有任何效果。 我的数组取自 HTTP 获取请求,但我认为它没有太大变化。 在我的 TypeScript 文件中,我有对象数组,但是如果我尝试在那里更改样式,则没有任何效果。

TypeScript:
export class TypeObjectComponent implements OnInit {
  object: Objects[];
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private service: ObjectService
  ) { }
  ngOnInit() {
    this.service.getType().subscribe(data => {
      this.object= data;
    })
  }

  HTML:
  <div class="form-group">
            <label for="typeO" ><b>Type</b></label>
            <select value="E" class="form-control" id="single" name="type">
              <option [ngStyle]="{'text-decoration': line-through}" *ngFor="let Objects of object; index as i">
              {{i}} - {{ Objects.type}}
            </option>
            </select>
        </div>

【问题讨论】:

  • 您的代码中没有使用ngStyle
  • 尝试使用类添加更多类并为其编写 css 并仅更改类

标签: javascript html angular typescript http


【解决方案1】:

一个问题是,在您的 [ngStyle] 中,您需要在值 line-through 周围加上引号,因为在这种情况下,这是一个 JavaScript 对象值,而不是 CSS 值。

该更改应该成功地将text-decoration: line-through 应用于您的option 元素。

但是,这可能无法实现您的目标,即通过它显示第二个项目(如果我正确理解您的目标),因为 select 中的 option 元素是 replaced element,所以即使使用应用该样式时,该元素将不会显示为直通。来自 MDN:

在 CSS 中,被替换元素是指其表示超出 CSS 范围的元素;它们是外部对象,其表示与 CSS 格式化模型无关...被替换元素的位置可以使用 CSS 影响,但不会影响被替换元素本身的内容。

因此,如果您需要在下拉选项中自定义样式,您可能需要使用 select 元素以外的其他元素。

【讨论】:

    【解决方案2】:

    使用您定义的索引值在您的第二个元素上添加一个类,并根据该类在您的 css 文件中写入您想要的任何样式。例如,在 html 中查看已编辑的部分。

     TypeScript:
        export class TypeObjectComponent implements OnInit {
          object: Objects[];
          constructor(
            private route: ActivatedRoute,
            private router: Router,
            private service: ObjectService
          ) { }
          ngOnInit() {
            this.service.getType().subscribe(data => {
              this.object= data;
            })
          }
    
      HTML:
      <div class="form-group">
                <label for="typeO" ><b>Type</b></label>
                <select value="E" class="form-control" id="single" name="type">
                  <option [ngClass]="{'line-through': i === 1}" *ngFor="let Objects of object; let i=index;">
                  {{i}} - {{ Objects.type}}
                </option>
                </select>
            </div>
    
    IN YOUR CSS:
    .line-though{
      text-decoration: line-through;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-03
      • 2020-01-04
      • 1970-01-01
      • 2019-04-24
      • 2021-10-18
      • 2018-05-26
      • 2018-12-05
      • 2017-04-06
      • 2019-04-07
      相关资源
      最近更新 更多