Angular2 new object in template
In Angular 2, you can create a new object in a template using the following approaches:
- Using the
ngOnInit
lifecycle hook:
In your component, you can create a new object in the ngOnInit
lifecycle hook, which is called after the component's constructor and before the component's view is initialized. You can then bind the object to a property in your component and use it in your template.
Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<div>{{ myObject }}</div>
`
})
export class ExampleComponent {
myObject: any;
ngOnInit() {
this.myObject = { name: 'John', age: 30 };
}
}
- Using a constructor:
You can also create a new object in the component's constructor and bind it to a property.
Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<div>{{ myObject }}</div>
`
})
export class ExampleComponent {
myObject: any;
constructor() {
this.myObject = { name: 'John', age: 30 };
}
}
- Using a function:
You can also create a new object in a function and bind it to a property.
Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<div>{{ myObject }}</div>
`
})
export class ExampleComponent {
myObject: any;
createMyObject() {
this.myObject = { name: 'John', age: 30 };
}
}
- Using a pipe:
You can also create a new object using a pipe. For example, you can use the json
pipe to convert an object to a JSON string.
Example:
import { Component } from '@angular/core';
import { json } from '@angular/common';
@Component({
selector: 'app-example',
template: `
<div>{{ myObject | json }}</div>
`
})
export class ExampleComponent {
myObject: any;
constructor() {
this.myObject = { name: 'John', age: 30 };
}
}
Note that in all cases, you need to bind the object to a property in your component using the =
syntax in your template.