在Angular 2中设置构造函数外部的值

在Angular 2中设置构造函数外部的值,angular,ecmascript-6,angular2-template,Angular,Ecmascript 6,Angular2 Template,我在构造函数外设置一个变量,并在模板中使用该变量,但它没有赋值。我怎样才能做到这一点 @Component({ selector: 'footer', template: ` <div> {{id}} {{name}} {{ans}} </div> `, }) export class App { id:number; name:string; ans:string; constructor() { this

我在构造函数外设置一个变量,并在模板中使用该变量,但它没有赋值。我怎样才能做到这一点

@Component({
  selector: 'footer',
  template: `
    <div>
      {{id}} {{name}} {{ans}}
    </div>
  `,
})
export class App {
  id:number;
  name:string;
  ans:string;
  constructor() {
    this.id = `1`,
    this.name = `App`
  }
  king = ()=>{
    this.ans = "variable";
    alert("Working");
  }
}

var sapp = new App();
sapp.king();
@组件({
选择器:“页脚”,
模板:`
{{id}{{name}{{{ans}}
`,
})
导出类应用程序{
id:编号;
名称:字符串;
ans:字符串;
构造函数(){
this.id=`1`,
this.name=`App`
}
国王=()=>{
this.ans=“变量”;
警惕(“工作”);
}
}
var sapp=新应用程序();
sapp.king();

以下是。

您可以使用
ngOnInit
方法

import {Component, NgModule, VERSION, OnInit} from '@angular/core'

ngOnInit() 
{
  this.id = `1.0.2`,
  this.name = `Helical`
}

如果在页面/视图加载时需要,可以初始化变量和声明。否则,您也可以使用ngOnInit执行相同的操作,但构造函数会在ngOnInit之前激发

export class App {
  id:number;
  name:string;
  ans:string= "variable";
  constructor() {
    this.id = `1`,
    this.name = `App`
  }
}
现在,您可以在模板中使用ans

 var sapp = new App();
上面这一行正在创建应用程序的新实例。通过这样做,您就有了两个应用程序实例。您正在调用新创建实例的
king()
方法。这就是为什么你不能让它发挥作用

要访问同一实例,请从任何生命周期方法调用
king()

例如


Updated

是否要在“king”方法中设置变量?为什么要显式创建组件的实例?您可以在ctor或ngOnInit生命周期钩子中调用king方法。
import {Component, OnInit} from '@angular/core'

   ngOnInit() 
   {
   king();
   }