簡體   English   中英

角度2-具有不同文本的相同組件

[英]Angular 2 - same component with different text

我想多次使用相同的組件,但使用不同的文本。 我怎樣才能做到這一點?

我的代碼:jumbotron.component.html:

<div class="jumbotron text-center">
   <h1 >{{jumbotronText}}</h1>
</div>

app.component.ts

@Component({
selector: 'my-app',
template: `
            <navbar></navbar>
            <jumbotron ></jumbotron>
            <jumbotron ></jumbotron>
            <jumbotron ></jumbotron>
            `
            ,
directives: [NavbarComponent, JumbotronComponent]})
export class AppComponent { }

我試圖這樣做:

        <jumbotron [jumbotronText]="My text to display"></jumbotron>

和這個:

        <jumbotron jumbotronText="My text to display"></jumbotron>

但是只有錯誤。 我認為這應該很容易,但是我找不到解決方法。

首先,您必須在Jumbotron組件中使用Input()批注標記jumbotronText:

@Component({
  selector: 'jumbotron',
  template: `
    <div class="jumbotron text-center">
      <h1 >{{jumbotronText}}</h1>
    </div>`
})
export class JumbotronComponent {
  //here is important line
  @Input() jumbotronText:string = "";
  constructor() { }
}

然后,您可以從調用方傳遞數據。 如果是靜態文本,則可以執行以下操作:

template: `
  <navbar></navbar>
  <jumbotron jumbotronText="One" ></jumbotron>
  <jumbotron jumbotronText="Two" ></jumbotron>
  <jumbotron jumbotronText="Three" ></jumbotron>`

如果是經過計算的文本,則可以執行以下操作:

template: `
  <navbar></navbar>
  <jumbotron [jumbotronText]="variableFromCaller1" ></jumbotron>
  <jumbotron [jumbotronText]="variableFromCaller2" ></jumbotron>
  <jumbotron [jumbotronText]="variableFromCaller3" ></jumbotron>`

也就是說,如果您在應用程序組件中具有存儲字符串(或方法,或者以其他方式計算出來的)的變量,則可以使用方括號指示單向綁定。 否則,如果您有靜態文本,則只需為Input()值分配與任何其他HTML標記屬性相同的值即可。

看到這個柱塞: https ://embed.plnkr.co/ve31cnEDidcLeEF7dfVj/

您將需要使用@Inputng-content 通過使用{{ }}語法,您將告訴Angular在jumbotronTextAppComponent名為jumbotronText的變量,但該變量不存在。

使用@Input()

jumbotron.component.html

<div class="jumbotron text-center">
    <h1>{{ jumbotronText }}</h1>
</div>

大分量組件

@Component({
    // ...
}) export class JumbotronComponent {

    @Input() jumbotronText: string;

    // ...
}

app.component.ts

@Component({
    selector: 'my-app',
    template: `
        <navbar></navbar>
        <jumbotron [jumbotronText]="My text to display"></jumbotron>
        `
        ,
    directives: [NavbarComponent, JumbotronComponent]})
export class AppComponent { }

使用ng-content

jumbotron.component.html

<div class="jumbotron text-center">
    <h1><ng-content></ng-content></h1>
</div>

app.component.ts

@Component({
    selector: 'my-app',
    template: `
        <navbar></navbar>
        <jumbotron>My text to display</jumbotron>
        `
        ,
    directives: [NavbarComponent, JumbotronComponent]})
export class AppComponent { }

添加到盧克的答案。 您必須從中導入Input批注

@angular/core

在屬性上使用@Input()注釋時。 您可以添加字符串作為參數,以使用別名引用屬性。 示例: @Input("customTitle") Private title:string;

您以后可以使用<my-directive [customTitle]="Custom" > </my-directive>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM