Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // App.tsx
- import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
- import { FormControl, NgForm } from '@angular/forms';
- import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators';
- @Component({
- selector: 'app-root',
- template: `
- <input type="text" [formControl]="textInput" #textRef>
- <hr>
- <app-weather
- [unit]="unit"
- [color]="fontColor"
- [city]="searchText"
- ></app-weather>
- <hr>
- <button (click)="unit = 'metric'">metric</button>
- <button (click)="unit = 'imperial'">imperial</button>
- <button (click)="fontColor = 'blue'">blue</button>
- <button (click)="fontColor = 'red'">red</button>
- `,
- })
- export class AppComponent implements OnInit, AfterViewInit {
- @ViewChild('textRef') textRef: ElementRef<HTMLInputElement>;
- textInput: FormControl = new FormControl();
- searchText = 'Milan';
- fontColor = 'red';
- unit = 'metric';
- constructor() {
- this.textInput.valueChanges
- .pipe(
- filter((text: string) => text.length > 3),
- debounceTime(1000),
- distinctUntilChanged()
- )
- .subscribe(text => {
- this.searchText = text;
- });
- // popolate text
- this.textInput.setValue(this.searchText);
- // focus text
- console.log('App: constructor', this.textRef)
- }
- ngOnInit(): void {
- console.log('App: init', this.textRef)
- }
- ngAfterViewInit(): void {
- console.log('App: after view', this.textRef)
- this.textRef.nativeElement.focus();
- }
- search(): void {
- console.log(this.textInput.value)
- }
- }
- // ============================
- // WeatherComponents
- import { AfterViewInit, Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
- import { HttpClient } from '@angular/common/http';
- import { Meteo } from '../model/meteo';
- @Component({
- selector: 'app-weather',
- template: `
- <h1 [style.color]="color">{{meteo?.main.temp}} °</h1>
- <img [src]="'http://openweathermap.org/img/w/' + meteo?.weather[0].icon + '.png'" alt="">
- `,
- })
- export class WeatherComponent implements AfterViewInit, OnChanges {
- @Input() city: string;
- @Input() unit: string;
- @Input() color: string;
- meteo: Meteo;
- constructor(private http: HttpClient) {}
- init(): void {
- console.log('WeatherComponent: init')
- }
- ngOnChanges(changes: SimpleChanges): void {
- if (changes.color && changes.color.firstChange) {
- this.init();
- }
- if (changes.color) {
- console.log('WeatherComponent: changes')
- }
- if (changes.city || changes.unit) {
- this.http.get<Meteo>(`http://api.openweathermap.org/data/2.5/weather?q=${changes.city.currentValue}&units=${this.unit}&APPID=eb03b1f5e5afb5f4a4edb40c1ef2f534`)
- .subscribe(res => this.meteo = res)
- }
- }
- ngAfterViewInit(): void {
- console.log('WeatherComponent: after view')
- }
- }
Add Comment
Please, Sign In to add comment