这里的 square 是个变量不是字符串,要让它是字符串应该加上引号。
[nzStrokeLinecap]="'square'"
获取 dom 元素:
* 可以通过 @ViewChil 获取【父子组件关系】的dom元素
export class ProtocolComponent implements OnInit {
@ViewChild(ProtocolMenuComponent, {static: false}) getKeyEsc: ProtocolMenuComponent | any;
//...
constructor(private el: ElementRef) {}
ngOnInit() {
console.log("father & child",this.el.nativeElement.querySelector('.card-list'))
}
}
ngAfterViewInit() {
console.log(this.getKeyEsc.nativeElement.innerHTML);
this.getKeyEsc.nativeElement.innerHTML = "DOM updated succesfully!!!";
}
demo: https://stackblitz.com/edit/angular-8-viewchild-example-rwrpri
不用【if】用【filter】:马克
不好的写法:
const x = fromEvent(this.el.nativeElement, 'keydown');
x.subscribe((key: KeyboardEvent | any) => {
if (key.keyCode == 27) {
console.log("key esc")
overlayRef.detach()
}
}, (e) => console.error(e))
好的写法:
enum KeyCode {
ESC = 27
}
fromEvent<KeyboardEvent>(this.el.nativeElement, 'keydown')
.pipe(filter(k => k.keyCode == KeyCode.ESC))
.subscribe(
() => {
overlayRef.detach();
},
e => console.error(e)
);
export class AppComponent implements AfterViewInit {
name = 'Angular';
@ViewChild(HelloComponent, {static: false}) hello: HelloComponent | any;
@ViewChild('div3', {static: false}) div3: ElementRef;
ngAfterViewInit() {
console.log('Hello ', this.hello.name);
}
constructor(private el:ElementRef,
private renderer2: Renderer2) {}
ngOnInit() {
console.log(this.el.nativeElement);
console.log("222");
console.log(this.el.nativeElement.querySelector('p'))
// console.log(this.div3.nativeElement); 失败???
this.renderer2.setStyle(this.el.nativeElement.querySelector('.btn1'),'background','red');
}
}
以上代码在控制台打印如下:
马克:https://stackoverflow.com/questions/50355584/observable-fromevent-rxjs
ngAfterViewInit() {
Observable.fromEvent(this.elementRef.nativeElement, 'keyup')
.pipe(
debounceTime(this.debounceTime),
distinctUntilChanged()
)
.subscribe(x => {
this.onDebounce.emit(x);
});
}
pipe
上面我们已经基本理解了fromEvent 的基本使用方法,主要分析的是subscribe 方法,我们现在有个需求,我们要控制Button , 在3s 时间内, 我们只能点击一次, 以防止,恶意点击按钮.Rxjs 都是基于流来操作,Observable 对象提供了一个pipe(管道)的方法, 在进入到subscribe 订阅者方法之前,所以的数据需要进行加工,异常处理, 以保证subscribe收到的是正确的数据
一个简单的操作符demo
ngOnInit() {
const x = of(2,3,4);
const y = x.pipe(
filter(n => n>3),
map((n:number)=>n * 2))
y.subscribe(x => {console.log(x)})
}
import { Subject, Observable, from } from 'rxjs';
const subject = new Subject<number>();
subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
next: (v) => console.log(`observerB: ${v}`)
});
subject.next(1);
// subject.next(2);
// 分割
const observable = from([10, 20, 30]);
const subscriptionX = observable.subscribe(x => console.log(x));
const subscriptionY = observable.subscribe(x => console.log(x, 233));
控制台打印如下: