【问题标题】:Changing text and setting a default更改文本并设置默认值
【发布时间】:2020-09-15 15:52:22
【问题描述】:

这是我常用的 Angular 组件“messageforStudents”。

学生信息.html:

<span>{{firstText}}</span>
<span>{{secondText}}</span>

messageforStudents.ts:

firstText = "Default text 1.";
secondText = "Default text 2.";

我将在任何地方使用上述组件与该文本。

但是当我在schoolRules.html 中使用messageforStudents 组件时,我想更改&lt;span&gt;{{firstText}}&lt;/span&gt;&lt;span&gt;{{secondText}}&lt;/span&gt; 的文本。我该怎么做?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    通过使用输入属性,您可以传递如下数据。

    messageForStudents.ts

    @Input() firstText = "Default text 1.";
    @Input() secondText = "Default text 2.";
    

    schoolRules.component.html

    <message-students [firstTest]="changedValueFirst" [secondText]="changedValueSecond"></message-students>
    

    schoolRules.component.ts

    changedValueFirst="Custom String 1";
    changedValueSecond= "Custom String 1";
    

    在其他组件中像这样使用它:-

    <message-students></message-students>
    

    【讨论】:

    • 您的解决方案的一部分帮助了我。谢谢! +10
    【解决方案2】:

    您可以在角度中使用@Input

    类似的东西

    @Input firstText = "Default text 1.";
    @Input secondText = "Default text 2.";
    

    然后使用组件

    <MessageforStudents [firstText]="foo" [secondText]="bar"></MessageforStudents>
    

    如果您不通过firstTextsecondText,它将采用您设置的默认值。

    【讨论】:

      【解决方案3】:

      用@Input 装饰器装饰firstText = "Default text 1."; 变量;

      @Input() firstText = "Default text 1.";
      
      <messageforStudents [firstText]="any other text"></messageforStudents>
      

      你可以对 secondText 进行类似的操作;

      如果您没有将任何值作为输入 &lt;messageforStudents&gt;&lt;/messageforStudents&gt; 传递,它将回退到您在组件中分配的默认文本,即 "Default text 1." 并显示它

      【讨论】:

        猜你喜欢
        • 2019-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-29
        • 1970-01-01
        • 1970-01-01
        • 2012-07-03
        相关资源
        最近更新 更多