1

我尝试了以下代码,但它不起作用。

import { Component } from '@angular/core';
import { TitleCasePipe } from '@angular/common';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  title = 'Working with Pipe';
  testValue = this.titleCasePipe.transform('firstletter should be upper case.');


  constructor(
    public titleCasePipe: TitleCasePipe
  ){}

}

在此处输入图像描述

4

4 回答 4

2

在组件元数据的 providers 数组中添加 TitleCasePipe :

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
providers: [TitleCasePipe]
})

Stackblitz 示例

于 2020-04-14T11:25:59.283 回答
1

您可以只创建一个对象,否则,像@Gérôms 所说的那样添加提供者

  title = 'Working with Pipe';
  titleCasePipe=new TitleCasePipe()
  testValue = this.titleCasePipe.transform('firstletter should be upper case.');

  constructor(){
  }
于 2020-04-14T11:37:49.667 回答
0

像这样将您的代码放入构造函数中,

 testValue: string;


 constructor(
    public titleCasePipe: TitleCasePipe
 ){
    this.testValue = this.titleCasePipe.transform('firstletter should be upper case.');
 }
于 2020-04-14T11:29:18.920 回答
0

无管


这是您的简单解决方案TitleCase

你可以像这样直接使用你不必把额外的代码角已经给了这个功能

HTML

<p>
  {{name | titlecase}} <!-- this is titlecase by default -->
</p>

TS

name = 'Working with Pipe';

带管

你也可以像这样签入input字段

HTML

<input type="text" id="firstName" name="name" 
[ngModel]="name | titleCase" 
(ngModelChange)="name=$event" 
#firstName="ngModel">

TS

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'titleCase'})
export class TitleCasePipe implements PipeTransform {
    public transform(input:string): string{
        console.log(input);
        if (!input) {
            return '';
        } else {
            return input.replace(/\b\w/g, first => first.toLocaleUpperCase()) 
        }
    } 
}

并且不要忘记declaration像这样添加

declarations: [ TitleCasePipe ],

这是我的 stackBlitz你可以在这里查看

于 2020-04-14T11:45:37.767 回答