【问题标题】:Angular - Conditional attribute of an elementAngular - 元素的条件属性
【发布时间】:2018-12-23 10:52:47
【问题描述】:

我正在使用基于Bootstrap's grid systemion-grid。这是我用于不同范围元素的代码的简化版本:

<ion-grid>
  <ion-row *ngFor="let task of allTasks">
    <ion-col *ngIf="task.author === this.currentUser" offset-3 col-9 class="task">
       <div>{{task.description}}</div>
     </ion-col>
  </ion-row>                                                              
</ion-grid>

我的 ion-grid 有 12 列。 offset-3 基本上会将元素推到列的最右边。但是,我希望通过两种方式有条件地更改此属性:

  1. 如果特定条件成立,请不要将offset-3 应用于此元素。正确的语法是什么:myCondition ? "offset-3" : ""

  2. 如何动态更改offset-{value}?假设我将col-auto 分配给上面的元素,如何更改offset-{value}{value} 使其不小于3 或更大?例如。 col-autocol-6 分配给元素,将 offset-{value} 更改为 offset-6 - 或者简单地将元素推到列的最右侧。

我不确定 2. 是否真的可以实现,但是任何能达到我想要的结果的解决方法对我来说都足够了。

【问题讨论】:

    标签: angular typescript ionic-framework grid conditional


    【解决方案1】:

    在您的组件中创建一个@input 属性,然后您可以将值传递给您的html; 偏移{{输入值}} 只是也许在你的组件中做更多的逻辑。并将值传递给 html,以便您在设置 HTML 之前检索该值。

    例子;

    your components.ts;
    
      @Input() value: string;
    
    
    You create a new method lets say;
    
    getOffsetValue() {
    
    if (x === foo) {
    this.value = '1';
    }else {
    this.value = '2';
    }
    return this.value
    }
    
    ngOnInit()
    
    // call method
    
    getOffsetValue();
    
    So now you have a data on the value attribute
    
    in your HTML;
    offSet{{this.value}}
    

    【讨论】:

    • 您认为可以提供一个示例代码来执行此操作吗?我尝试了以下方法:&lt;ion-col *ngIf="task.author === this.currentUser" offset{{this.inputValue}} col-9 class="task"&gt; 但它只是导致了这个错误:Failed to execute 'setAttribute' on 'Element': 'offset{{this.inputValue}}' is not a valid attribute name..
    • 在手机上输入这个可能看起来很难看,但希望你明白这一点 - 试图提供一个伪示例
    猜你喜欢
    • 2016-10-19
    • 2021-03-30
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多