首页 > 解决方案 > 具有属性的自定义组件

问题描述

我想知道如何在 Ionic 3 中创建我们自己的具有某些属性的组件。一个例子是离子按钮的“完整”属性。我想要做的是渲染我自己的组件,它看起来像这样

<my-component my-property></my-component>

标签: propertiesionic3

解决方案


我强烈推荐 angular.io 网站上的任何基础教程。

您想要的是 Ionic 正在利用的 Angular 的基础。

看这里我为你构建了一个简单的例子: https ://stackblitz.com/edit/ionic-f9bq9h

您在 ts 文件中定义组件:

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

@Component({
  selector: 'my-component',
  template: `<div>{{ myProperty }}</div>`
})
export class MyComponent {

  @Input('myProperty') myProperty: string;

  constructor() {

  }

}

确保它被适当地添加到 app.module.ts

然后您可以在导入它的其他组件中使用它:

<ion-content padding>
  <h2>Welcome to Ionic!</h2>
  <p>
    This starter project comes with simple tabs-based layout for apps
    that are going to primarily use a Tabbed UI.
  </p>
  <p>
    Take a look at the <code>pages/</code> directory to add or change tabs,
    update any existing page or create new pages.
  </p>
  <my-component [myProperty]="'I am a custom component'"></my-component>
</ion-content>

推荐阅读