簡體   English   中英

在 Angular 中從一個組件更改另一個組件中的變量

[英]Changing a variable from one component in another component in Angular

考慮 FirstComponent 和 SecondComponent。

在 first.component.html 中,假設我有:

[...]
<input>
<app-second><app-second/>
[...]

假設我們正在瀏覽器中查看 first.component.html。 假設所有SecondComponent所做的只是顯示一些形狀,如圓形和東西,以及一個邊長為input的正方形,由用戶輸入。

所以在second.component.html中,我有:

<svg>
  < some other SVG elements here >
  ...
  <rect width="height" height="height" />
  ...
</svg>

其中“高度”是second.component.ts中的變量:

imports ...

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.scss'],
})
export class SecondComponent{


  height: string;
  width: string;

所以基本上,我想將作為SecondComponent中的變量的heightwidth更改為任何input ,即 FirstComponent 中的HTML元素。

這是一種假設情況,實際上這是針對我正在制作像 MS Paint 這樣的在線繪圖平台的項目,這個特殊情況是讓用戶設置網格大小

    <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
        <defs>
            <pattern id="smallGrid" width="8" height="8" patternUnits="userSpaceOnUse">
                <path id="myPath" d="pathString" fill="none" stroke="black" stroke-width="1" />
            </pattern>
        </defs>   
        <rect id="myGrid" [style.opacity]="opacityValue"  width="100%" height="100%" fill="url(#smallGrid)"/>
    </svg>

我在這里嘗試更改的值是pathString (確定構成字符串的正方形的大小)和opacityValue ,顧名思義,它是網格的不透明度。 這些是CanvasComponent中的變量。

我試過的:

我嘗試制作一個服務GridService但后來我在網上看到你也可以使用@Input()? 訪問另一個組件中的變量? 我還看到在另一個線程中使用了@ViewChild。 我只是不確定該怎么做。

提前致謝!

在您的模板中:

<input #widthInput> <app-second [width]="widthInput.value"><app-second/>

在 TS 文件中:

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.scss'],
})
export class SecondComponent{


  height: string;
 @Input() width: string
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM