Как настроить Ionic 3 кнопки для динамического выделения или обводки? - PullRequest
0 голосов
/ 02 ноября 2018

У меня есть несколько кнопок в приложении Ionic 3, которые я бы хотел динамически устанавливать как контурные или четкие. Я могу связать clear сам по себе, и это работает (случай 1 ниже). И я могу связать outline сам (случай 2 ниже). Но когда я пытаюсь связать clear и outline, кажется, что значение outline игнорируется. Я показал желаемый результат в самом последнем ряду.

У меня есть это как часть класса для моей страницы:

  buttons = [
          {clear: true, outline: false, name: 'Clear'},
          {clear: false, outline: true, name: 'Outline'},
          {clear: false, outline: false, name: 'Default'},
        ];

А мой HTML-код:

<ion-content padding>
  <ion-row>
    <ion-col col-6>
      <ion-label>
        1. Binding clear attribute:
      </ion-label>
    </ion-col>
    <ion-col col-2 *ngFor="let button of buttons">
      <button ion-button
        [clear]="button.clear">
        {{button.name}}
      </button>
    </ion-col>
  </ion-row>
  <ion-row>
    <ion-col col-6>
      <ion-label>
        2. Binding outline attribute:
      </ion-label>
    </ion-col>
    <ion-col col-2 *ngFor="let button of buttons">
      <button ion-button
        [outline]="button.outline">
        {{button.name}}
      </button>
    </ion-col>
  </ion-row>
  <ion-row>
    <ion-col col-6>
      <ion-label>
        3. Binding clear and outline attributes:
      </ion-label>
    </ion-col>
    <ion-col col-2 *ngFor="let button of buttons">
      <button ion-button
        [outline]="button.outline"
        [clear]="button.clear">
        {{button.name}}
      </button>
    </ion-col>
  </ion-row>
  <ion-row>
    <ion-col col-6>
      <ion-label>
        4. Desired output:
      </ion-label>
    </ion-col>
    <ion-col col-2>
      <button ion-button clear>Clear</button>
    </ion-col>
    <ion-col col-2>
      <button ion-button outline>Outline</button>
    </ion-col>
    <ion-col col-2>
      <button ion-button>Default</button>
    </ion-col>
  </ion-row>
</ion-content>

Вот рендеринг страницы: enter image description here

И Плункер с полным кодом: https://embed.plnkr.co/eFBFc9/

Есть ли причина, по которой я не смогу связываться с clear и outline?

Я понимаю, что мог бы использовать ngIf, чтобы в конечном итоге достичь того же результата:

<button ion-button *ngIf="button.clear" clear>{{button.name}}</button>
<button ion-button *ngIf="button.outline" outline>{{button.name}}</button>
<button ion-button *ngIf="!button.clear && !button.outline">{{button.name}}</button>

Но кажется, что было бы более кратким иметь одну кнопку с несколькими связанными атрибутами. Как мне этого добиться?

Я также попробовал attr.clear и attr.outline вместо clear и outline, но мне тоже не повезло.

1 Ответ

0 голосов
/ 02 ноября 2018

Это похоже на ошибку в Ionic, но вы все равно можете создать свой собственный пользовательский компонент, чтобы «скрыть» исправление, которое включает использование трех кнопок с *ngIf и использование этого пользовательского компонента на ваших страницах.


Демонстрация StackBlitz


Ваш пользовательский компонент может выглядеть следующим образом:

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

@Component({
  selector: 'custom-button',
    template: `
    <button (click)="onClick()" ion-button *ngIf="clear" clear>{{name}}</button>
    <button (click)="onClick()" ion-button *ngIf="outline" outline>{{name}}</button>
    <button (click)="onClick()" ion-button *ngIf="!clear && !outline">{{name}}</button>
  `,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomButtonComponent {

  @Input() 
  public clear: boolean = false;

  @Input() 
  public outline: boolean = false;

  @Input() 
  public name: string;

  @Output() 
  customClick: EventEmitter<void> = new EventEmitter<void>();

  public onClick(): void {
    this.customClick.next();
  }

}

И тогда вы будете использовать это на своих страницах:

import { Component } from '@angular/core';

@Component({
  selector: 'page-home',
  template: `
    <ion-header>
      <ion-navbar>
        <ion-title>Home</ion-title>
      </ion-navbar>
    </ion-header>

    <ion-content padding>
      <h2>Welcome to Ionic!</h2>

      <ion-row>
        <ion-col col-6>
          <ion-label>
            Using the custom component:
          </ion-label>
        </ion-col>
        <ion-col col-2 *ngFor="let button of buttons">

          <custom-button
            [clear]="button.clear ? true : null"       
            [outline]="button.outline ? true : null"
            [name]="button.name"
            (customClick)="onClicked()">
          </custom-button>

        </ion-col>
      </ion-row>

    </ion-content>
  `
})
export class HomePage {

  public buttons: Array<any> = [
    { clear: true, outline: false, name: 'Clear' },
    { clear: false, outline: true, name: 'Outline' },
    { clear: false, outline: false, name: 'Default' }
  ];

  public onClicked() {
    console.log('Clicked!');
  }

}
...