角度:在组件外部设置组件属性

时间:2018-10-18 18:39:58

标签: angular typescript components

我有一个使用组件显示其某些属性的Angular页面。但是组件的属性不会显示在页面上。这是代码:

HTML页面(testPage.component.html)

<p>title: {{title}}</p>
<p>another title: {{anotherTitle}}</p>

TypeScript(testPage.component.ts)

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

@Component({
  selector: 'app-testPage',
  templateUrl: './testPage.component.html',
  styleUrls: ['./testPage.component.css']
})
export class TestPageComponent implements OnInit {
  title: string;
  anotherTitle = "This is another title";

  setTitle(): void {
    this.title = "This is title!!";
    console.log('This is title', this.title);
  }
}

var testPageComponent = new TestPageComponent();
//newBudgetComponent.title = "some title here!!"; //Also not working
testPageComponent.setTitle();

在页面中,anotherTitle的填充很好,但是title的填充没有。

函数setTitle记录标题,但“角度”页面不显示该值。

页面外观如下:

enter image description here

如何在组件外部设置组件属性?

2 个答案:

答案 0 :(得分:0)

您是否要设置页面标题?如果是这样,请使用标题服务

import { Title } from '@angular/platform-browser';

constructor(private titleService: Title)

this.titleService.setTitle("Title");

否则,请使用带有行为主题的共享服务,除非它是子组件,然后使用Input

答案 1 :(得分:0)

有几种方法可以实现这一目标。首先,与您试图显示示例的示例相比,Angular中组件的交互以及它们在页面上的显示方式要简单一些。请参阅this link,以了解有关Angular中组件生命周期的更多信息。

关于在组件上设置属性值的示例如下。请记住,其中一些可能需要调整,因为我没有在IDE中编写它/运行代码。

您的示例已经做到了。创建组件时,该字段的默认值已经设置。 title = 'My Title'

使用@Input()装饰属性可让您将数据从父组件传递到子组件。 <my-child-component [title]='value-or-variable'></my-child-component>

使用@ViewChild()装饰器装饰“组件”属性(在本例中为父组件的子组件),将允许父组件访问子组件并使用其属性。请记住,指示的组件必须是父组件的子组件。 @ViewChild(MyChildComponent) child: MyChildComponent;,然后在完成父组件的初始化周期后this.child.title = 'My Title';

使用@ContentChild()装饰器装饰“ component”属性(在这种情况下,父级或任何后代中的子级组件)将允许父级组件访问后代组件并与它们的后代一起使用,并且属性。请记住,指示的组件可以是此父级的任何后代组件。 @ContentChild(MyDescendentComponent) descendent: MyDescendentComponent;,然后在初始化周期完成之后this.descendent.title = 'My Title';

可以将提供的对象注入到组件中,并在ngOnInit方法中理想地设置该组件的值。可以将提供程序设置为几个不同的级别,包括(但不限于)组件模块。 This link在依赖注入方面更加深入,即使它稍老一些。

class MyComponent {
  constructor(myService: MyService) {}
}
//module
providers: [
  MyTitleToken,
],

//component
class MyComponent {
  constructor(public title: MyTitleToken) {}
}
//module
providers: [
  {provide: 'MyTitle', useValue: 'Hello Title'},
],

//component
class MyComponent {
  constructor(@Inject('MyTitle') title: string) {}
}
相关问题