Использовать компонент в другом компоненте в Angular - PullRequest
0 голосов
/ 18 апреля 2020

Я новый пользователь Angular и работаю над сайтом, чтобы улучшить свое обучение. Но есть кое-что, что я считаю очень простым, но не работает. Я работаю над портфолио дизайнеров движений, где компонент будет повторно использоваться для демонстрации работ по движению. Но в этот момент я заблудился и не знаю, как все это организовать ... Как повторно использовать компонент portfolio-card.com с различными заголовками, изображениями, URL-адресами и помещать его в мой projects.component? Спасибо за помощь! Ура!

motion.ts

export interface Motion {
  id: number;
  title: string;
  image: string;
  url: string;
}

motion-mock.ts


export const Motions: Motion[] = [
  { "id": 1, "title": "Demoreel 2D/3D", "image": "", "url": "https://vimeo.com/314625743" },
  { "id": 2, "title": "Le défi Martin Fourcade MGEN 2018", "image": "", "url": "https://vimeo.com/260561771"},
  { "id": 3, "title": "Voeux 2018 SERCEL", "image": "", "url": "https://vimeo.com/251785754" },
]

portfolio-card.component.ts

import { Component, OnInit } from '@angular/core';
import { Motions } from './motion-mock.ts';

@Component({
  selector: 'app-portfolio-card',
  templateUrl: './portfolio-card.component.html',
  styleUrls: ['./portfolio-card.component.scss']
})
export class PortfolioCardComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

Портфолио-card.component. html

<div class="col-md-4 col-sm-6 animate-box" data-animate-effect="fadeInLeft">
  <div class="blog-entry">
    <div class="card" >
      <img class="card-img-top" src="{{myMotion.image}}" alt="{{myMotion.title}}" style="width:100%">
        <div class="card-body">
          <h4 class="card-title">{{motion.title}}</h4>
          <h5 class="card-text"></h5>
          <h5 class="card-text"><a href="{{myMotion.url}}">{{myMotion.title}}</a></h5>        
        </div>
    </div>
  </div>
</div> 

projects.component.ts

import { Component, OnInit } from '@angular/core';
import { PortfolioCardComponent } from './portfolio-card/portfolio-card.component';

@Component({
  selector: 'app-projects',
  templateUrl: './projects.component.html',
  styleUrls: ['./projects.component.scss']
})
export class ProjectsComponent implements OnInit {
  pageTitle: string = "Motion design";

  constructor() { }

  ngOnInit() {
  }

}

Ответы [ 2 ]

0 голосов
/ 18 апреля 2020

1.Измените ваш PortfolioCardComponent, чтобы принять движение в качестве параметра:

import { Component, OnInit, Input } from '@angular/core';
import { Motion } from './motion';

@Component({
  selector: 'app-portfolio-card',
  templateUrl: './portfolio-card.component.html'
})
export class PortfolioCardComponent implements OnInit {
  @Input() myMotion: Motion;
  constructor() { }

  ngOnInit() {
  }

}

2. Измените ваш projects.component.ts, чтобы получить все предложения:

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

@Component({
  selector: 'app-projects',
  templateUrl: './projects.component.html',
  styleUrls: ['./projects.component.scss']
})
export class ProjectsComponent implements OnInit {
  pageTitle: string = "Motion design";
    motions = Motions;

  constructor() { }

  ngOnInit() {
  }

}

3. Наконец, вы можете отрисовать все движения в вашем projects.component. html:

<ng-template ngFor let-item [ngForOf]="motions">
  <app-portfolio-card [myMotion]="item"></app-portfolio-card>
</ng-template>

См. Рабочий пример по этой ссылке: https://stackblitz.com/edit/angular-sxrrbu

0 голосов
/ 18 апреля 2020

Прежде всего, нет необходимости импортировать его внутрь projects.component.ts.

Вместо этого

импортируйте его в файл module.ts и добавьте его в массив declarations.

и в файле project.component. html используйте его следующим образом:

<h1>{{ pageTitle }}</h1>
...
<app-portfolio-card></app-portfolio-card>
...

, куда хотите.

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