import { Component, OnInit } from '@angular/core';
然后要使用方法OnInit,我们必须像这样实现类:
export class App implements OnInit {constructor() {// Called first time before the ngOnInit()}
ngOnInit() {// Called after the constructor and called after the first ngOnChanges()}}
#0:constructor是在构建组件时default method运行(默认)。当你创建一个类的an instance时,也会调用constructor(default method)。换句话说,当组件constructed or/and an instance is created constructor(default method)被调用并在其中编写相关代码时,会被调用。基本上和一般在Angular2中,它用于在构建组件以供进一步使用时注入像services这样的东西。
import {Cmomponent, OnInit} from 'angular2/core';import {ExternalService} from '../externalService';
export class app implements OnInit{constructor(myService:ExternalService){this.myService=myService;}
ngOnInit(){// this.myService.someMethod()}}
export class User {email: string;password: string;lastLogin: Date;
constructor(msg:string) {this.email = "";this.password = "";this.lastLogin = new Date();console.log("*** User class constructor " + msg + " ***");}
Login() {}}
login.component.ts
import {Component} from "@angular/core";import {User} from "./../../shared/user/user"
@Component({selector: "login-component",templateUrl: "pages/login/login.html",styleUrls: ["pages/login/login-common.css", "pages/login/login.css"]})export class LoginComponent {
user: User = new User("property"); // ONEisLoggingIn:boolean;
constructor() {this.user = new User("constructor"); // TWOconsole.log("*** Login Component Constructor ***");}
ngOnInit() {this.user = new User("ngOnInit"); // THREEthis.user.Login();this.isLoggingIn = true;console.log("*** Login Component ngOnInit ***");}
submit() {alert("You’re using: " + this.user.email + " " + this.user.lastLogin);}
toggleDisplay() {this.isLoggingIn = !this.isLoggingIn;}
}
控制台输出
JS: *** User class constructor property ***JS: *** User class constructor constructor ***JS: *** Login Component Constructor ***JS: *** User class constructor ngOnInit ***JS: *** Login Component ngOnInit ***
import {Component} from '@angular/core';@Component({})class CONSTRUCTORTEST {
//This is called by Javascript not the Angular.constructor(){console.log("view constructor initialised");}}
export class App implements OnInit, AfterViewInit, AfterContentInit {@Input() myInput: string;@ViewChild() myTemplate: TemplateRef<any>;@ContentChild(ChildComponent) myComponent: ChildComponent;
constructor(private elementRef: ElementRef) {// this.elementRef.nativeElement is undefined here// this.myInput is undefined here// this.myTemplate is undefined here// this.myComponent is undefine here}
ngOnInit() {// this.elementRef.nativeElement can be used from here on// value of this.myInput is passed from parent scope// this.myTemplate and this.myComponent are still undefined}ngAfterContentInit() {// this.myComponent now gets projected in and can be accessed// this.myTemplate is still undefined}
ngAfterViewInit() {// this.myTemplate can be used now as well}}