我有一个像
我想得到这样的东西:
my beutifull super <a (click)="urlHandler(URLLINK)">URLLINK</a> with no doorway!
如何动态地在代码中生成模板元素?
最佳答案
欢迎鲍勃·巴尔孔斯基!
我们可以将此功能放在一个单独的组件中,
@Component({
selector: 'app-custom-string-transformer',
template: `{{parsed.before || ''}}<a *ngIf="parsed.url" (click)="handleUrlClick(parsed.url)">{{parsed.url}}</a>{{parsed.after || ''}}`,
styles: [`a { color: blue; text-decoration: underline; cursor: pointer;}`]
})
export class StringTransformerComponent implements OnInit {
@Input() str: string
@Output() onUrlClicked: EventEmitter<string> = new EventEmitter<string>();
parsed: ParsedString = {} as ParsedString
ngOnInit(): void {
this.parsed = this._parseStr(this.str)
}
_parseStr(str: string): ParsedString {
const [full, before, url, after] = str.match(/(.*)%url%(.+)%url%(.*)/)
return {before, url, after}
}
handleUrlClick(url: string): void {
this.onUrlClicked.emit(url);
}
}
演示:https://stackblitz.com/edit/angular-nakjdb?file=src%2Fapp%2Fstring-transformer.component.ts