Angular 8: определить, есть ли в ng-контенте контент (или он существует) - PullRequest
2 голосов
/ 25 июня 2019

У меня есть компонент, шаблон которого допускает 2 области содержимого: текст и текст «читать дальше».Если потребитель компонента добавляет область для текста «читать дальше», я хочу показать ссылку «читать дальше», которую конечный пользователь щелкнул бы, чтобы показать текст.Если они не включают / не нуждаются в каком-либо тексте «читать дальше», я не хочу показывать ссылку.

Как я могу определить наличие области шаблона и действовать соответственно с ngIf?

Например, html может быть:

<app-promohero-message-unit title="Title for messaging module">
     <div description>
       Include a short, informative description here.
     </div>
     <div readmoretext>
       If you need to add more detail, include another sentence or two it in this section.
     </div>
</app-promohero-message-unit>

Очевидно, что им может не понадобиться readmoretext, поэтому, если они его пропустили, я не должен показывать ссылку для чтения.

Код компонента на данный момент:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-promohero-message-unit',
  template: `
    <div>
      <h3 class="text-white">{{ title }}</h3>
      <p class="text-white">
        <ng-content select="[description]"></ng-content>
      </p>
      <p class="text-white" *ngIf="readMore">
        <ng-content select="[readmoretext]"></ng-content>
      </p>
    </div>
    <p>
      <a class="text-white" (click)="showReadMore()" *ngIf="something"><u>Read more</u></a>
    </p>
  `
})
export class PromoheroMessageUnitComponent {
  @Input()
  title: string;

  readMore = false;

  showReadMore() {
    this.readMore = true;
  }
}

Ответы [ 2 ]

2 голосов
/ 26 июня 2019

Вы можете получить ссылку на ng-content ( переменную шаблона ) и затем получить доступ к этой переменной в своем компоненте, чтобы проверить длину содержимого этого ng-content, используя ViewChild

Затем вы можете использовать ngAfterViewInit ловушку жизненного цикла, чтобы проверить ng-content длину

Ваш код будет таким:

import { Component, Input, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-promohero-message-unit',
  template: `
    <div>
      <h3 class="text-white">{{ title }}</h3>
      <p class="text-white">
        <ng-content select="[description]"></ng-content>
      </p>
      <p class="text-white" *ngIf="readMore">
        <ng-content #readMoreContent select="[readmoretext]"></ng-content>
      </p>
    </div>
    <p>
      <a class="text-white" (click)="showReadMore()" *ngIf="something"><u>Read more</u></a>
    </p>
  `
})
export class PromoheroMessageUnitComponent {
  @Input()
  title: string;
  @ViewChild('readMoreContent') readMoreContent: ElementRef;

  readMore = false;

  ngAfterViewInit() {
    if (this.readMoreContent.nativeElement.childNodes.length.value == 0){
      this.readMore = false
    }
  }

  showReadMore() {
    this.readMore = true;
  }
}
1 голос
/ 26 июня 2019

В Angular 8 вам не нужно использовать хук жизненного цикла ngAfterViewInit.Вы можете использовать ngOnInit, если для «статического» значения viewchild установлено значение true.

import { Component, OnInit, ViewChild, TemplateRef, ElementRef } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
  @ViewChild('content', { read: ElementRef, static: true }) content: ElementRef;
  constructor() { }

  ngOnInit() {
    console.log(!!this.content.nativeElement.innerHTML);  // return true if there is a content
  }
}

Обратите внимание, что вы должны обернуть директиву ng-content тегом html (например, div, span и т. Д.).) и установить templateRef для этого внешнего тега.

<div #content>
  <ng-content></ng-content>
</div>

Я поместил его в стек стека: https://stackblitz.com/edit/angular-8-communicating-between-components-mzneaa?file=app/app.component.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...