我需要向现有组件添加一个名为“dataTestValue”的新属性。这是一个简单的组件,其作用类似于选项卡:
export class TabComponent implements OnInit {
@Input('active') active = false;
@Input('title') title: string;
dataTestValue: string;
constructor() { }
ngOnInit() {
this.dataTestValue = this.title.replace('/ /g', '_');
console.log(this.dataTestValue);
}
}
因为“title”属性可能包含空格,我需要将其替换并将其转换为小写。
我设法使用以下方法仅替换第一个空白:
this.dataTestValue = this.title.replace(' ', '_');
由于某种原因,全局方法不起作用,它只是打印原始值。有什么想法吗?
P.S:如果我使用“ngOnInit”生命周期 Hook ,请通知我。
最佳答案
从正则表达式中删除单引号:
this.dataTestValue = this.title.replace(/ /g, '_');
关于javascript - 在 Angular 2+ 组件中使用全局替换方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801384/