当前位置:网站首页>Typescript decorator
Typescript decorator
2022-07-24 08:32:00 【lvxinaidou】
1. Define a decorator , The function under the decorator will trigger automatically
app.component.html
<button nz-button nzType="primary" (click)="method(obj)">decorator</button>
app.component.ts
import {
Component, OnInit,} from '@angular/core';
import {
Color } from './core/learn-decorator';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
public title:string = '';
public operate:string = 'add';
constructor() {
}
ngOnInit() {
}
obj = {
name: 'lxing', age: 30}
@Color('red')
method(e) {
console.log(e); // {name: 'lxing', age: 30}
console.log('method!!!!!owner');
}
// selectValue(e) {
// console.log(e);
// }
}
Decorator
export function Color(value:string):Function {
//red
console.log(value);
return function(target:Object, key:string | symbol, descriptor:PropertyDescriptor) {
// {constructor: class AppCompent, ngOnInit(), method: fucntion.....}
console.log(target);
// Function name method()
console.log(key);
// {configuable: true, enumerable: false, value: function()......, writable: true}
console.log(descriptor);
const original = descriptor.value;
descriptor.value = function(...args:any) {
// [{name: 'lxing', age: 30}]
console.log(args);
// There must be these two lines , Only in this way can the external event callback be triggered .
const result = original.apply(this, args);
console.log(result)
return result;
}
return descriptor;
}
}
You can also specify the name of the function , In this way, the triggered function can be placed in any position
The changed code
import {
Component, OnInit,} from '@angular/core';
import {
Color } from './core/learn-decorator';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
public title:string = '';
public operate:string = 'add';
constructor() {
}
ngOnInit() {
}
obj = {
name: 'lxing', age: 30}
@Color('red', 'method')
selectValue(e) {
console.log(e);
}
method(e) {
console.log(e); // {name: 'lxing', age: 30}
console.log('method!!!!!owner');
}
}
export function Color(value:string, methodName: string):Function {
//red
console.log(value);
return function(target:Object, key:string | symbol, descriptor:PropertyDescriptor) {
// {constructor: class AppCompent, ngOnInit(), method: fucntion.....}
console.log(target);
// Function name method()
console.log(key);
// {configuable: true, enumerable: false, value: function()......, writable: true}
console.log(descriptor);
const original = descriptor.value;
descriptor.value = function(...args:any) {
// [{name: 'lxing', age: 30}]
console.log(args);
// There must be these two lines , Only in this way can the external event callback be triggered .
const result = original.apply(this, args);
console.log(result)
return result;
}
return descriptor;
}
}
Use scenarios : Dialog box ,ngOnChanges Encapsulation , Reduce duplicate code
father.html + ts
<input [(ngModel)]="title"/>
<app-child [title]="title" [operate]="operate"></app-child>
public title:string = '';
public operate:string = 'add';
child.html + ts
<h1>{
{
title}}--{
{
operate}}</h1>
import {
Component, OnInit, Input, OnChanges } from '@angular/core';
import {
TrackChanges } from 'src/app/core/learn-decorator';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.less']
})
export class ChildComponent implements OnChanges {
@Input() title : string = '';
@Input() operate: string = '';
@TrackChanges('title', 'changeDetails')
ngOnChanges() {
console.log('do some operate!!!');
}
changeDetails() {
console.log('value change');
// this.title = 'title'
}
}
Decorator
export function TrackChanges<Type>(key: string, methodName: string): Function {
return function (targetClass, functionName: string, descriptor): Function {
const source = descriptor.value;
descriptor.value = function (changes: SimpleChanges): Function {
console.log(changes);
if (changes && changes[key] && changes[key].currentValue !== undefined) {
console.log(targetClass);
console.log(targetClass[methodName]);
targetClass[methodName].call(this, changes[key].currentValue as Type);
}
return source.call(this, changes);
};
return descriptor;
};
}


边栏推荐
- [MySQL] 08: aggregate function
- Wxml template concise tutorial
- Upload and insert the execle table into the database based on ThinkPHP
- Overseas media, domestic we media, media publicity
- Confusing defer, return, named return value, anonymous return value in golang
- Grpc learning notes
- Figure storage geabase
- Digital collections are both outlets and risks!
- Wargames bandit (21-33) problem solving essay
- Hack the box - Web requests module detailed Chinese tutorial
猜你喜欢

Larave uses sanctum for API authentication

Wei Xiaoli's "pursuer" is coming

SVG 从入门到后悔,怎么不早点学起来(图解版)

About the big hole of wechat applet promise

Wechat payment V3 version of openresty implementation and pit avoidance Guide (service side)
![[Linux] Oracle VirtualBox installation CentOS 8](/img/fc/ea1070b93d3f1dbc52e60045834ea9.png)
[Linux] Oracle VirtualBox installation CentOS 8

Optimization of MySQL paging query

Move protocol launched a beta version, and you can "0" participate in p2e

国产“火箭心”人工心脏上市 不同人工心脏有什么区别?

Will Plato become the risk target of the meta universe? Platofarm has great opportunities
随机推荐
Web3 traffic aggregation platform starfish OS interprets the "p2e" ecosystem of real business
Is yuancosmos hype? Or the future
3587. Connected graph (Jilin University postgraduate entrance examination machine test question)
FPGA integrated project - image edge detection system
图新地球:Revit建模的rvt格式BIM模型如何带着纹理精准匹配地图
"Solution" friend of Vulcan
Wechat official account configures custom menu jump applet and automatically replies to jump applet
JS string interception
[redis] how much do you know about bloom filter and cuckoo filter?
Advantages and disadvantages of redis and ZK implementing distributed locks
Uva572 oil deposits problem solution
Selenium webdriver page refresh
【一起上水硕系列】一起提前看看July课程
JMX Console 未授权访问漏洞
P1739 expression bracket matching problem solution
Wechat payment V3 version of openresty implementation and pit avoidance Guide (service side)
Draw a circular radar chart with canvas
Move protocol launched a beta version, and you can "0" participate in p2e
【一起上水硕系列】EE feedback 详解
Go:gin write test code