Skip to content

Instantly share code, notes, and snippets.

@tjoskar
Last active May 22, 2016 14:04
Show Gist options
  • Save tjoskar/71e0dce55e75e90db971 to your computer and use it in GitHub Desktop.
Save tjoskar/71e0dce55e75e90db971 to your computer and use it in GitHub Desktop.
Angular 2 chapter 1 solution
import { Component } from '@angular/core';
@Component({
selector: 'my-input',
template: `
<input [(ngModel)]="username">
<!--
Same as:
<input [value]="username" (keyUp)="username=$event.target.value">
-->
<br />
{{username}}
`
})
class MyInputComponent {
username = 'Jesse';
}
export default MyInputComponent;
export { MyInputComponent };
import { Component } from 'angular2/core';
@Component({
selector: 'my-input',
template: `
<input [value]="username" #input>
<br />
<button (click)="onClick(input.value)">Click me!</button>
<br />
{{username}}
`
})
class MyInputComponent {
username = 'Jesse';
onClick(username) {
this.username = username;
}
}
export { MyInputComponent };
// OR (POC):
import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'my-input',
template: `
<input [value]="username" (keyup)="update($event.target.value)">
<br />
<button (click)="rerender()">Click me!</button>
<br />
<p [innerHTML]="username"></p>
`
})
class MyInputComponent {
username = 'Jesse';
cd: ChangeDetectorRef;
constructor(cd: ChangeDetectorRef) {
this.cd = cd;
}
update(username) {
this.cd.detach();
this.username = username;
}
rerender() {
this.cd.reattach();
}
}
export { MyInputComponent };
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'city-dropdown',
template: `
<select (change)="onChange($event.target.value)" [value]="city">
<option value=""></option>
<option value="Ankarsrum">Ankarsrum</option>
<option value="Västervik">Västervik</option>
<option value="Stockholm">Stockholm</option>
</select>
`
})
class CityComponent {
@Input() city;
@Output() cityChange = new EventEmitter();
onChange(city) {
this.cityChange.emit(city);
}
}
@Component({
selector: 'my-input',
template: `
<input [(ngModel)]="username">
<city-dropdown [city]="city" (cityChange)="city = $event"></city-dropdown>
<!--
Same as above:
<city-dropdown [(city)]="city"></city-dropdown>
-->
<br />
Username: {{username}}
<br />
City: {{city}}
`,
directives: [CityComponent]
})
class MyInputComponent {
username = 'Jesse';
city = 'Stockholm';
}
export default MyInputComponent;
export { MyInputComponent };
import { Component } from '@angular/core';
@Component({
selector: 'my-input',
template: `
<p *ngFor="let i of numbers">{{i}}</p>
<!--
Same as:
<template ngFor let-i [ngForOf]="numbers">
<p>{{i}}</p>
</template>
-->
`,
})
export class MyInputComponent {
numbers = [1, 2, 3, 4];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment