How to write custom components in Ionic 2/3 withou

2020-02-11 06:00发布

问题:

When I write my own custom component like this:

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

@Component({
  selector: 'deletableItem',
  template: `
    <ion-checkbox item-right></ion-checkbox>
  `
})
export class DeletableItem {
  constructor() {}
}

And use it in some html view:

<ion-content padding>
  <ion-list>
    <ion-item *ngFor="let bill of bills" (click)="openEdit(bill)">
      <ion-label text-left>{{bill.name}}</ion-label>
      <deletableItem></deletableItem>
    </ion-item>
  </ion-list>
</ion-content>

The looking of it is worse than just put it in parent's component view at once like this:

<ion-content padding>
  <ion-list>
    <ion-item *ngFor="let bill of bills" (click)="openEdit(bill)">
      <ion-label text-left>{{bill.name}}</ion-label>
      <ion-checkbox item-right></ion-checkbox>
    </ion-item>
  </ion-list>
</ion-content>

All this because angular wrap this component's html code into html tag. So we lose ionic components strengths (prepared css). Please do not suggest attributive component assignment like:

<ion-checkbox item-right deletableItem></ion-checkbox>

Because this is just simple example.

What is the best way to write custom components with ionic components inside without losing prepared css?

回答1:

You have to realise Ionic is using SASS and targets multiple platforms. When you create your <deletableItem></deletableItem> you have should mimic what the ionic team did with ion-checkbox, and create you Sass files.

Check out the source folder here for <ion-checkbox>.

Define your own SASS for deleteableItem.

Furthermore, on the Ionic website you can find the various SASS component/platform variables.

I also gave a detailed related explanation, regarding Ionic CSS classes assignment that may help you too.

You can also use Chrome inspect to see class assignments for ion-checkbox in the Developer tool, and compare them to the list on the Ionic website.