Angular2: как показать внутренний HTML тегов компонентов внутри компонента?

У меня вопрос по angular2. Я создаю некоторые компоненты и хочу иметь что-то вроде этого:

Это мой класс DogComponent:

@Component({
    selector: "dog",
    template: "dog.template.html"
})
class DogComponent
{
    @Input() image: string;
}

И шаблон в dog.template.html:

<div>
    <!-- Content of <top> should go here -->
    <img class="after" src="dogs/{{image}}" />
    <!-- Content of <bottom> should go here -->
</div>

Когда я использую DogComponent, он должен создать тег img с переданным src, а также просмотреть другие части HTML до и после изображения.

Итак, в конце концов, если я напишу этот код:

<dog image="garry.png">
    <top>
        <h1>This is Garry!</h1>
    </top>
    <bottom>
        <span>He is my favorite dog!</span>
    </bottom>
</dog>

это должно быть отнесено к этому:

<dog>
    <div>
        <h1>This is Garry!</h1>
        <img src="dog.png" />
        <span>He is my favorite dog!</span>
    </div>
</dog>

У кого-нибудь есть ответ на мой вопрос?

Было бы здорово!

Изменить:

Спасибо за советы, теперь я обновил свои фрагменты и добавил DogListComponent. Последний фрагмент (результат браузера) следует просмотреть, если я использую тег dog-list где-то в своем приложении. Надеюсь, теперь стало немного понятнее.

dog.component.ts

@Component({
    selector: "dog",
    templateUrl: "dog.template.html"
})
class DogComponent
{
    @Input() image: string;
}

dog.template.html

<div>
    <!-- Content of <top> should go here -->
    <img class="after" src="dogs/{{image}}" />
    <!-- Content of <bottom> should go here -->
</div>

dog_list.component.ts

@Component({
    selector: "dog-list",
    templateUrl: "dog-list.template.html"
})
class DogListComponent
{
}

список собак.template.html

<dog image="garry.png">
    <top>
        <h1>This is Garry!</h1>
    </top>
    <bottom>
        <span>He is my favorite dog!</span>
    </bottom>
</dog>
<dog image="linda.png">
    <top>
        <h1>My little Linda :)</h1>
    </top>
    <bottom>
        <span>She is my cutest dog!</span>
    </bottom>
</dog>
<dog image="rex.png">
    <top>
        <h1>And here is Rex!</h1>
    </top>
    <bottom>
        <span>DANGEROUS!</span>
    </bottom>
</dog>

Результат браузера:

<dog-list>
    <dog image="garry.png">
        <top>
            <h1>This is Garry!</h1>
        </top>
        <bottom>
            <span>He is my favorite dog!</span>
        </bottom>
    </dog>

    <dog image="linda.png">
        <top>
            <h1>My little Linda :)</h1>
        </top>
        <bottom>
            <span>She is my cutest dog!</span>
        </bottom>
    </dog>

    <dog image="rex.png">
        <top>
            <h1>And here is Rex!</h1>
        </top>
        <bottom>
            <span>DANGEROUS!</span>
        </bottom>
    </dog>
<dog-list>

person be-ndee    schedule 20.01.2017    source источник
comment
Вы имеете в виду, что он должен отображать его в редакторе/IDE, который вы используете? Или это через DOM - что он и делает, если вы его проверяете. Также это templateUrl не шаблон   -  person Katana24    schedule 20.01.2017
comment
Он должен отображаться в скомпилированном/рендеринговом DOM при запуске приложения. Пытаюсь добиться, чтобы комментарий <!-- Content of <top> should go here --> в dog.template.html заменялся тегом <top><h1>This is Garry!</h1></top>, указанным в dog-list.template.html.   -  person be-ndee    schedule 21.01.2017


Ответы (2)


Итак, я нашел свое решение! Мне нужно использовать <ng-content>.

dog.template.html выглядит так:

<div>
    <ng-content select="top"></ng-content>
    <img class="after" src="dogs/{{image}}" />
    <ng-content select="bottom"></ng-content>
</div>

Затем он вставит указанные <top>-tags и <bottom>-tags в мой div.

person be-ndee    schedule 23.01.2017

Похоже, вы неправильно понимаете роль селектора. Селектор <dog></dog> будет использоваться другими компонентами (например, AppComponent) для отображения HTML-кода вашего компонента собаки. Таким образом, нет смысла использовать селектор в собственном компоненте HTML.

Кроме того, если вы хотите использовать внешний файл в качестве шаблона, используйте синтаксис templateUrl, а не template. так :

@Component({
selector: "dog",
templateUrl: "dog.template.html" // make sure the path to the file is correct

В dog.template.html просто поместите свой HTML-код:

<div>
    <h1>This is Garry!</h1>
    <img src="dogs/{{image}}" /> 
    <!-- the component deliver the value image (dog.png) to your template -->
    <span>He is my favorite dog!</span>
</div>

Изменить, чтобы ответить на обновленный код. Насколько я понимаю, у вас есть множество собак, pictures доступных из dog_list.component.ts. Вы используете их в своем шаблоне с чем-то вроде *ngFor="let picture of pictures". Вы не говорите, как выглядят ваши данные, но, возможно, вы можете попробовать это, если у вас есть массив, отформатированный как arr = [{'topTile':'This is Garry!', 'picture': 'garry.png', 'bottomTitle':'He is my favorite dog!' }, {}, ...]

 <!-- Parent component template (dog_list) --> 
   <div *ngFor="let data of arr">
        <top>
            <h1>{{ data.topTitle }}</h1> <!-- This is Garry!, ... -->
        </top>
        <dog [image]="data.picture"></dog><!-- Bind data to children component dog with value garry.png -->
        <bottom>
            <span>{{ data.bottomTitle }}</span> <!-- He is my favorite dog!,... -->
        </bottom> 
    </div>

Для более подробной информации, возможно, могут помочь документы по синтаксису шаблонов angular: https://angular.io/docs/ts/latest/guide/template-syntax.html

person mickdev    schedule 20.01.2017
comment
Спасибо за templateUrl, это был просто пример, в реальном приложении я все делаю правильно ;) И с селектором я тоже разбираюсь. В моем случае я пытаюсь поместить некоторые другие теги извне DogComponent (в обновленном вопросе из DogListComponent) в DogComponent. - person be-ndee; 21.01.2017