Angular 2 - 具有不同文本的相同组件

时间:2016-08-19 15:48:14

标签: data-binding angular components

我想多次使用相同的组件,但文本不同。我怎么能这样做?

我的代码: 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>

但只有错误。我认为这应该很容易,但我不知道如何解决这个问题。

3 个答案:

答案 0 :(得分:3)

首先,您必须使用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>`

也就是说,如果app组件中有变量存储字符串(或方法,或以其他方式计算),则使用方括号表示单向绑定。否则,如果您有静态文本,则只需将Input()值指定为与任何其他HTML标记属性相同。

请参阅此Plunker:https://embed.plnkr.co/ve31cnEDidcLeEF7dfVj/

答案 1 :(得分:0)

您需要使用@Inputng-content。通过使用{{ }}语法,您告诉Angular在jumbotronText中查找名为AppComponent的变量,但这不存在。

使用@Input()

jumbotron.component.html

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

jumbotron.component.ts

@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 { }

答案 2 :(得分:0)

加入卢克的答案。您必须从

导入comma(,)注释
Input

在属性上使用@angular/core 注释时。您可以添加字符串作为参数,以使用别名引用属性。 例:  @Input()   @Input("customTitle")

您可以稍后使用 Private title:string;