【问题标题】:Change properties at component decorator Angular 2 from class从类更改组件装饰器 Angular 2 的属性
【发布时间】:2016-12-20 07:46:50
【问题描述】:

我想在某些操作发生后更改模板

@Component({
  ... 
  template: this.myTemplate
})

export class App {
  myTemplate: = 'Here is first template';

  // Replace templates
  public changeTempate() {
    myTemplate = 'Here is second template';
  }

如何使这段代码工作?

【问题讨论】:

  • 您的用例到底是什么?有很多可能的选择,具体取决于您尝试执行的操作。
  • 我要更改模板(html)
  • 这不是一个用例。我说的是您在这里尝试实现的目标的背景。让我解释一下——从技术上讲,你所要求的是不可能的,因为 Angular 在你的类逻辑执行之前编译模板是 JIT(及时)或 AOT(提前)。但是您可以选择绑定[innerHTML] 或使用*ngIf 有条件地显示两个组件。但是除非我知道这里的实际用例,否则我不能向您推荐一个。

标签: angular typescript components


【解决方案1】:

最后它是在 Angular 2.3.0 中制作的 这是一个简单的示例:

//our root app component
import {Component, NgModule, Input, Output, EventEmitter, HostBinding, HostListener} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'person',
  //template will NOT be inherited 
  template: `<h4>Person: {{name}}</h4>`
})
export class Person {
  @Input() name; //will be inherited
  //  @Output() onClick = new EventEmitter(); //will be inherited
  //  clicked() { //will be inherited
  //    this.onClick.emit(this.name);
  //  }
  @HostBinding('style.color') color = 'red';  //will be inherited

  @HostListener('click', ['$event']) //will be inherited 
  onClick(e){
    console.log(this.name);
  }
}

@Component({
  selector: 'employee',
  template: `
    <h4>Employee: {{name}}, id: {{id}}</h4>
  `
})
export class Employee extends Person {
  @Input() id; // new

  @HostListener('click', ['$event']) // overridden
  onClick(e) { 
    console.log(`${this.name}-${this.id}`);
  }
}


@Component({
  selector: 'my-app',
  template: `
    <div>
      <person name="John"></person>
      <employee name="Tom" id="45231"></employee>
    </div>
  `,
})
export class App { }

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, Person, Employee ],
  bootstrap: [ App ]
})
export class AppModule {}

更多信息请阅读

https://medium.com/@gerard.sans/angular-2-new-features-in-angular-2-3-f2e73f16a09e#.33fk3molt

【讨论】:

    猜你喜欢
    • 2017-03-15
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多