@angular/core#PipeTransform TypeScript Examples

The following examples show how to use @angular/core#PipeTransform. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: timeline-score-formater.pipe.ts    From one-platform with MIT License 6 votes vote down vote up
@Pipe({
  name: 'timelineScoreFormater',
})
export class TimelineScoreFormaterPipe implements PipeTransform {
  formatDate = new DatePipe(this.locale);
  constructor(@Inject(LOCALE_ID) private locale: string) {}

  parseTimeLineForAScoreType(scoreType: string, branch: ProjectBranch[]) {
    return branch
      .filter(({ score }) => Boolean(score)) // filter out null score
      .map(({ score, updatedAt }) => ({
        name: this.formatDate.transform(updatedAt, 'MMM-dd, h:mm'),
        value: score?.[scoreType] || 0,
      }));
  }

  transform(value: ProjectBranch[], ...args: unknown[]) {
    const scoreLabelFormater = new LHScoreLabelFormaterPipe();
    const scores = [
      'pwa',
      'accessibility',
      'seo',
      'bestPractices',
      'performance',
    ];

    return scores
      .sort((a, b) => a[0].localeCompare(b[0]))
      .map((scoreType) => ({
        name: scoreLabelFormater.transform(scoreType),
        series: this.parseTimeLineForAScoreType(scoreType, value),
      }));
  }
}
Example #2
Source File: time.pipe.ts    From TypeFast with MIT License 6 votes vote down vote up
@Pipe({
  name: 'time',
})
export class TimePipe implements PipeTransform {
  transform(value: number): string {
    const seconds = value % 60;
    const minutes = ((value - seconds) % 3600) / 60;
    const hours = (value - minutes * 60 - seconds) / 3600;

    return `${hours > 0 ? hours + ':' : ''}${
      hours > 0 ? this.pad(minutes) + ':' : minutes > 0 ? minutes + ':' : ''
    }${minutes > 0 || hours > 0 ? this.pad(seconds) : seconds + ''}`;
  }

  pad(value: number) {
    let res = value + '';
    while (res.length < 2) {
      res = '0' + res;
    }

    return res;
  }
}
Example #3
Source File: base64-parse.pipe.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
@Pipe({
  name: 'base64Parse'
})
export class Base64ParsePipe implements PipeTransform {

  transform(value: string | Buffer): unknown {
    if (typeof value === 'string') {
      return atob(value);
    } else {
      return atob(value.toString());
    }
  }

}
Example #4
Source File: big-number-format.pipe.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
@Pipe({ name: 'bigNumberFormat' })
export class BigNumberFormatPipe implements PipeTransform {
  /**
   * Converts number to {@link BIG_NUMBER_FORMAT}.
   * @param value number to convert
   * @param dp decimal places
   * @param toFixed true if decimals in converted number must be strictly equal to {@param dp},
   * false if decimal places can be less than or equal to {@param dp}
   */
  transform(value: BigNumber | string | number, dp = -1, toFixed = false): string {
    if (typeof value === 'number') {
      value = value.toString();
    }

    if (!value) {
      return '';
    }

    if (typeof value === 'string') {
      value = new BigNumber(value.split(',').join(''));
    }

    if (dp !== -1) {
      return !toFixed
        ? value.dp(dp).toFormat(BIG_NUMBER_FORMAT)
        : value.toFormat(dp, BIG_NUMBER_FORMAT);
    }

    return value.toFormat(BIG_NUMBER_FORMAT);
  }
}
Example #5
Source File: escape-url.pipe.ts    From FireAdmin with MIT License 6 votes vote down vote up
@Pipe({
  name: 'escapeUrl',
  pure: false
})
export class EscapeUrlPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) { }

  transform(content: string|any) {
    return this.sanitizer.bypassSecurityTrustUrl(content);
  }

}
Example #6
Source File: camel-case.pipe.ts    From canopy with Apache License 2.0 6 votes vote down vote up
@Pipe({
  name: 'camelCase',
})
export class LgCamelCasePipe implements PipeTransform {
  transform(str: string): string {
    return !str
      ? str
      : str
        .replace(/(['"])/g, '')
        .replace(/(?:^\w|[A-Z]|\b\w)/g, (ltr, idx) =>
          idx === 0
            ? ltr.toLowerCase()
            : ltr.toUpperCase(),
        )
        .replace(/(\s|-|\/|')/g, '');
  }
}
Example #7
Source File: search-by-login.pipe.ts    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
@Pipe({
  name: 'searchByLogin'
})
export class SearchByLoginPipe implements PipeTransform {

  transform(members: MemberEntity[], value: string): MemberEntity[] {
    return members.filter(
      member => member.login.toLowerCase().includes(value.toLowerCase())
    );
  }

}
Example #8
Source File: champions.pipe.ts    From league-profile-tool with MIT License 6 votes vote down vote up
@Pipe({
  name: 'champions',
  pure: false
})
export class ChampionsPipe implements PipeTransform {
  transform(items: any[], filter: string): any {
    if (!items || !filter) {
      return items;
    }
    // filter items array, items which match and return true will be
    // kept, false will be filtered out
    return items.filter(item => item.alt.toLowerCase().indexOf(filter.toLowerCase()) !== -1);
  }

}
Example #9
Source File: safe-url.pipe.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
@Pipe({
  name: 'safeUrl'
})
export class SafeUrlPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) { }

  transform(url: string): SafeResourceUrl {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }

}
Example #10
Source File: safe.pipe.ts    From nica-os with MIT License 6 votes vote down vote up
@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {

  constructor(protected sanitizer: DomSanitizer) {}

  public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
      case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
      case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
      case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
      case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
      default: throw new Error(`Invalid safe type specified: ${type}`);
    }
  }
}
Example #11
Source File: detail.pipe.ts    From leapp with Mozilla Public License 2.0 6 votes vote down vote up
@Pipe({
  name: "detail",
})
export class DetailPipe implements PipeTransform {
  transform(session: Session): string {
    switch (session.type) {
      case SessionType.awsIamRoleFederated:
        return (session as AwsIamRoleFederatedSession).roleArn.split("role/")[1] || "";
      case SessionType.azure:
        return (session as AzureSession).subscriptionId;
      case SessionType.awsIamUser:
        return ""; // (sessions as AwsIamUserSession).sessionName;
      case SessionType.awsSsoRole:
        const splittedRoleArn = (session as AwsSsoRoleSession).roleArn.split("/");
        splittedRoleArn.splice(0, 1);
        return splittedRoleArn.join("/");
      case SessionType.awsIamRoleChained:
        return (session as AwsIamRoleChainedSession).roleArn.split("role/")[1] || "";
    }
  }
}
Example #12
Source File: mult-table.pipe.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
@Pipe({
  name: 'multTable',
})
export class MultTablePipe implements PipeTransform {
  transform(_, digit: number, limit: number): Array<string> {
    if (!digit || !limit) {
      return [];
    }
    return new Array(Math.floor(limit)).fill(0).map((_, index) => {
      return `${digit} * ${index + 1} = ${digit * (index + 1)}`;
    });
  }
}
Example #13
Source File: asset-units.pipe.ts    From thorchain-explorer-singlechain with MIT License 6 votes vote down vote up
@Pipe({
  name: 'assetUnits'
})
export class AssetUnitsPipe implements PipeTransform {

  transform(value: unknown, unit: number): unknown {

    const int = Number(value);

    if (typeof int === 'number') {
      return int / 10 ** unit;
    } else {
      console.error(`error parsing ${value} into number`);
      return '-';
    }

    return null;
  }

}
Example #14
Source File: app-name.pipe.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Resolves to the name of an application's symbolic name.
 */
@Pipe({name: 'devtoolsAppName'})
export class AppNamePipe implements PipeTransform {

  constructor(private _manifestService: DevToolsManifestService) {
  }

  public transform(symbolicName: string): string | undefined {
    return this._manifestService.getApplication(symbolicName)?.name;
  }
}
Example #15
Source File: sanitize-html.pipe.ts    From SideQuest with MIT License 6 votes vote down vote up
@Pipe({
  name: 'sanitizeHtml'
})
export class SanitizeHtmlPipe implements PipeTransform {

  constructor(private _sanitizer:DomSanitizer) {
  }

  transform(v:string):SafeHtml {
    return this._sanitizer.bypassSecurityTrustHtml(v);
  }
}
Example #16
Source File: translate.pipe.ts    From colo-calc with Do What The F*ck You Want To Public License 6 votes vote down vote up
@Pipe({
  name: '_',
  pure: false
})
export class TranslatePipe implements PipeTransform {

  constructor(private languageService: LanguageService) {}

  transform(label: LabelKeys): string {
    return this.languageService.getLabel(label);
  }

}
Example #17
Source File: OrderBy.Pipe.ts    From CloudeeCMS with Apache License 2.0 6 votes vote down vote up
@Pipe({ name: 'orderBy' })
export class OrderByPipe implements PipeTransform {
    transform(records: Array<any>, args?: any): any {
        return records.sort((a, b) => {
            const iA = a[args.property] || '';
            const iB = b[args.property] || '';
            if (iA < iB) {
                return -1 * args.direction;
            } else if (iA > iB) {
                return 1 * args.direction;
            } else {
                return 0;
            }
        });
    }
}
Example #18
Source File: download-count.pipe.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
@Pipe({
  name: "downloadCount",
})
export class DownloadCountPipe implements PipeTransform {
  public constructor(private translateService: TranslateService) {}

  public transform(value: number): string {
    const numMatches = /(e\+\d+)/.exec(value.toExponential());
    if (!numMatches) {
      throw new Error("Failed to get matches");
    }

    const suffix = numMatches[1];

    const params = {
      rawCount: value,
      count: shortenDownloadCount(value, 3),
      simpleCount: shortenDownloadCount(value, 1),
      myriadCount: shortenDownloadCount(value, 4),
    };

    return suffix ? this.translateService.instant("COMMON.DOWNLOAD_COUNT." + suffix, params) : value.toString();
  }
}
Example #19
Source File: filter-brand.pipe.ts    From ReCapProject-Frontend with MIT License 6 votes vote down vote up
@Pipe({
  name: 'filterBrand',
})
export class FilterBrandPipe implements PipeTransform {
  transform(value: Brand[], filterText: string): Brand[] {
    return value.filter((b: Brand) =>
      b.name.toLocaleLowerCase().includes(filterText.toLocaleLowerCase())
    );
  }
}
Example #20
Source File: auth.pipe.ts    From ngx-admin-dotnet-starter with MIT License 6 votes vote down vote up
@Pipe({ name: 'ngxAuthToken' })
export class AuthPipe implements PipeTransform {
  constructor(private authService: NbAuthService) {}

  transform(url: string): Observable<string> {
    if (!url) {
      return observableOf(url);
    }
    return this.authService.getToken()
      .pipe(map((token: NbAuthToken) => {
        const separator = url.indexOf('?') > 0 ? '&' : '?';
        return `${url}${separator}token=${token.getValue()}`;
      }));

  }
}
Example #21
Source File: i18n.pipe.ts    From alauda-ui with MIT License 6 votes vote down vote up
@Pipe({
  name: 'auiI18n',
})
export class I18nPipe implements PipeTransform {
  constructor(private readonly i18n: I18nService) {}
  transform(value: any, data?: StringMap) {
    return this.i18n.translate(value, data);
  }
}
Example #22
Source File: add-commas.pipe.ts    From router with MIT License 6 votes vote down vote up
@Pipe({ name: 'bcAddCommas' })
export class AddCommasPipe implements PipeTransform {
  transform(authors: null | string[]) {
    if (!authors) {
      return 'Author Unknown';
    }

    switch (authors.length) {
      case 0:
        return 'Author Unknown';
      case 1:
        return authors[0];
      case 2:
        return authors.join(' and ');
      default:
        const last = authors[authors.length - 1];
        const remaining = authors.slice(0, -1);
        return `${remaining.join(', ')}, and ${last}`;
    }
  }
}
Example #23
Source File: safe-url.pipe.ts    From reactive-angular-course with MIT License 6 votes vote down vote up
@Pipe({
  name: 'safeUrl'
})
export class SafeUrlPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) {

  }

  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }

}
Example #24
Source File: country-placeholder.ts    From ion-intl-tel-input with MIT License 6 votes vote down vote up
@Pipe({name: 'countryPlaceholder'})
export class CountryPlaceholder implements PipeTransform {
  transform(country: CountryI, inputPlaceholder: string, separateDialCode: boolean, fallbackPlaceholder: string): string {
    if (inputPlaceholder && inputPlaceholder.length > 0) {
      return inputPlaceholder;
    }

    const phoneUtil = PhoneNumberUtil.getInstance();
    try {
      const placeholder = phoneUtil.format(phoneUtil.getExampleNumber(country.isoCode), PhoneNumberFormat.INTERNATIONAL);
      if (placeholder) {
        if (separateDialCode) {
          return placeholder.substr(placeholder.indexOf(' ') + 1);
        } else {
          return placeholder;
        }
      }
    } catch (e) {
      return fallbackPlaceholder;
    }
  }
}
Example #25
Source File: ago.pipe.ts    From blockcore-explorer with MIT License 6 votes vote down vote up
@Pipe({ name: 'ago' })
export class AgoPipe implements PipeTransform {
   transform(value: number): string {

      if (value === 0) {
         return '';
      }

      const date = moment.unix(value);
      return date.fromNow();
   }
}
Example #26
Source File: coin-notation.pipe.ts    From blockcore-hub with MIT License 6 votes vote down vote up
@Pipe({
    name: 'coinNotation'
})
export class CoinNotationPipe implements PipeTransform {
    private coinUnit: string | undefined;
    // private coinNotation: number;

    constructor(private globalService: GlobalService) {
        this.setCoinUnit();
    }

    transform(value: number): string {
      return this.globalService.transform(value);
    }

    getCoinUnit() {
        return this.coinUnit;
    }

    setCoinUnit() {
        this.coinUnit = this.globalService.getCoinUnit();
    }
}
Example #27
Source File: activity-date-display.pipe.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
@Pipe({
  name: 'activityDateDisplay'
})
export class ActivityDateDisplayPipe implements PipeTransform {

  constructor(private dateService: DateService) { }

  transform(activity: Activity): string {
    let display: string = '';

    if (activity) {
      if (activity.startDate) {
        let startDate: number = this.dateService.convertToLocal(activity.startDate);

        display = this.dateService.getShortDateAndTimeDisplay(startDate);

        if (activity.endDate) {
          let endDate = this.dateService.convertToLocal(activity.endDate);

          let startTimeDisplay: string = this.dateService.getShortTimeDisplay(startDate);
          let endTimeDisplay: string = this.dateService.getShortTimeDisplay(endDate);

          let startDateDisplay: string = this.dateService.getShortDateDisplay(startDate);
          let endDateDisplay: string = this.dateService.getShortDateDisplay(endDate);

          if (startDateDisplay == endDateDisplay) {
            display = startDateDisplay + " " + startTimeDisplay + " - " + endTimeDisplay;
          } else {
            display = display + " - " + this.dateService.getShortDateAndTimeDisplay(endDate);
          }
        }
      }
    }

    return display;
  }
}
Example #28
Source File: toNiceName.pipe.ts    From oss-github-benchmark with GNU General Public License v3.0 6 votes vote down vote up
@Pipe({ name: 'toNiceName' })
export class ToNiceNamePipe implements PipeTransform {
  sectors: { original: string; nice: string }[] = [
    { original: 'ResearchAndEducation', nice: 'Research and education' },
    { original: 'NGOs', nice: 'NGOs' },
    { original: 'Media', nice: 'Media' },
    { original: 'Insurances', nice: 'Insurances' },
    { original: 'IT', nice: 'IT' },
    { original: 'Gov_Federal', nice: 'Federal government' },
    { original: 'Gov_Companies', nice: 'Governmental companies' },
    { original: 'Gov_Cities', nice: 'Cities' },
    { original: 'Gov_Cantons', nice: 'Cantons' },
    { original: 'Communities', nice: 'Communities' },
    { original: 'Banking', nice: 'Banking and finance' },
    { original: 'Others', nice: 'Others' },
    { original: 'true', nice: 'Yes' },
    { original: 'false', nice: 'No' },
  ];

  transform(value: any): string {
    const name: any = this.sectors.find(
      (sector) => sector.original === value.toString()
    );
    return name ? name.nice : value;
  }
}
Example #29
Source File: data-property-getter.pipe.ts    From material-reusable-table with Apache License 2.0 6 votes vote down vote up
@Pipe({
  name: 'dataPropertyGetter'
})
export class DataPropertyGetterPipe implements PipeTransform {

  transform(object: any, keyName: string, ...args: unknown[]): unknown {
    return object[keyName];
  }

}