1

I'm tinkering with Angular2 and have found I am unable to initially populate a html input with values from the controller when the class Constructor is called. Strangely, the input does populates with the bound default data after the user tries to make a change to the value of the input. How do I initially set the value of a html input when the view first loads so that the input is pre-populated with text ?

This is the HTML template...

<div class="row">
    <div class="col-md-3">Username:</div>
    <div class="col-md-9"><input  [(ngModel)]="CurrentUser.Username" /></div>    
</div>
<div class="row">
    <div class="col-md-3">Password:</div>
    <div class="col-md-9"><input  [(ngModel)]="CurrentUser.Password" /></div>    
</div>
<div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-9"><button class="btn btn-sm btn-primary"     (click)="signin()">Sign in</button></div>    
</div>

Here is the Component (Controller)...

import {Component} from 'angular2/core'
import {UserService} from '../services/user-current.service';

@Component({
    templateUrl: './app/templates/signin.template.html'
})


export class SigninComponent { 
    private CurrentUser: UserService;    
    constructor(private userService:UserService) {
        this.CurrentUser = userService
    }  
}

for the sake of reference, I have included the service that loads the data I want displayed in the html input...

import {Injectable} from "angular2/core";

@Injectable()

export class UserService {

    private Username = "TEST";
    private Password = "Password";
    private UserID = 1;
    private LoggedIn = true;

    constructor() {}

    setUser(userObject) {
        this.Username = userObject.Username;
        this.Password = userObject.Password;
        this.UserID = userObject.UserID;
        this.LoggedIn = userObject.LoggedIn;
    }

}

also for complete clarity, here is the navigation component which is loading the view (including the SigninComponent)...

import {Component} from 'angular2/core'
import {RouteConfig,ROUTER_DIRECTIVES} from 'angular2/router'
import {UsersListComponent} from './users-list.component'
import {DashboardComponent} from './dashboard.component'
import {SigninComponent} from './signin.component'
import {UserService} from '../services/user-current.service';

@Component({
    selector: 'nav-top',
    templateUrl: './app/templates/nav-top.template.html',
    directives: [ROUTER_DIRECTIVES]
})


@RouteConfig([
    {path: '/users', name:'UsersList', component: UsersListComponent},
    {path: '/signin', name:'Signin', component: SigninComponent},
    {path: '/', name:'Dashboard', component: DashboardComponent, useAsDefault: true}
])

export class NavTopComponent{    
    private CurrentUser;    
    constructor(private userService:UserService) {
        this.CurrentUser = userService
    }       
}

I believe the issue is related to the use of ngOnInit which never seems to fire as the console.log() within the function does not fire. Here is an updated look at the code I'm now using for the SigninComponent...The ngOnInit does not fire.

import {Component,OnInit} from 'angular2/core'
import {UserService} from '../services/user-current.service';

@Component({
    selector: 'SigninComponent',
    templateUrl: './app/templates/signin.template.html',
    providers: [UserService]
})

export class SigninComponent implements OnInit{ 

    public CurrentUser;

    constructor(public userService:UserService) {   
        console.log("constructor");   
    } 

    ngOnInit() {
        this.CurrentUser = this.userService;
        console.log("ngOnInit");
    }

}
17
  • Nope. No errors...I've been copying my code from various tutorials online. I added the selector and providers properties, but that has made no difference. Commented Apr 29, 2016 at 1:49
  • SigninComponent is being loaded as a view using @RouteConfig. What I find most strange is that the html input values are updated, but only when the user enters a value into either of the inputs or clicks the button. Commented Apr 29, 2016 at 2:06
  • Strange it works on plunker but not on my localhost Commented Apr 29, 2016 at 2:07
  • Thanks for your suggestions. I changed the private to public in the UserService and also in the SigninComponent for good measure, but it's still not initializing when the view is loaded. Commented Apr 29, 2016 at 2:26
  • 1
    @acdcjunior has found the final piece of the puzzle. The <script> tags were out of order. Which was causing the ngOnInit not to fire. I'll post a complete solution shortly. Thanks everyone. Commented Apr 29, 2016 at 4:15

1 Answer 1

1

There were two parts to my problem.

Firstly, the constructor happens before some sort of Angular2 life cycle stuff that is way above my pay grade. Essentially, you need to import OnInit and then Implement OnInit in your exported class. Once you do this, you can use the ngOnInit function.

Secondly, this ngOnInit will not fire unless your tags are in the correct order. Firstly, here is the final Component code...

import {Component,OnInit} from 'angular2/core'
import {UserService} from '../services/user-current.service';

@Component({
    selector: 'SigninComponent',
    templateUrl: './app/templates/signin.template.html',
    providers: [UserService]
})



export class SigninComponent implements OnInit{ 

    public CurrentUser;

    constructor(public userService:UserService) {   
        console.log("constructor");   
    } 

    ngOnInit() {
        this.CurrentUser = this.userService;
        console.log("ngOnInit");
    }

}

Lastly, here is my scripts from the index.html in the order I needed to make it all work...

<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>     
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="node_modules/angular2/bundles/router.dev.js"></script>

Thanks to everyone who helped to find this answer. Credit should go to you...

Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.