czwartek, 20 kwietnia 2017

Angular2 - Cannot read property 'id' of undefined for ngModel

Lets take the following piece of code
 <form>
    <select [(ngModel)]="project.id"...
In this case when there is no 'project' value set yet it will be thrown an error with the following message: Cannot read property 'id' of undefined

Maybe '?' operator can help us? Let's try.

 <form>
    <select [(ngModel)]="project?.id"...
Nope, this will cause template parsing error: Parser Error: The '?.' operator cannot be used in the assignment at column 13 in [project?.id=$event]

And what about the ngIf directive?

 <form *ngIf="project" >
    <select [(ngModel)]="project.id"...
Ufff. It works ;)

wtorek, 4 kwietnia 2017

Angular2 - Two ways of injecting dependencies

There are two ways of delivering dependencies to the created object. One is the widely know "injection by type", which is done by specifying typed parameters in constructor.

Inject by Type

constructor(private service: MyService) {
}
This assumes MyService is imported specific class put into providers of your module.

Inject by Name

Another way is "injecting by name".

constructor(@Inject('myService') private service) {
}
This time we required the following in the module providers list
{provide: 'myService', useClass: MyService},
The main advantage of the latter is we actually get rid of importing specific class, though, decouple from other local resources

We can also provide values instead of classes:

{provide: 'url', useValue: 'http://localhost'},