angular - hata TS2339: JavaScript'ten TypeScript'e hata
src/app/dashboard.component.ts(49,15) HATASI: TS2339 hatası: 'Element' türünde 'style' özelliği mevcut değil. src/app/dashboard.component.ts(50,16) HATASI: TS2339 hatası: 'EventTarget' türünde 'textContent' özelliği mevcut değil.
Bu bir JavaScript fonksiyonu olarak çalışıyor, ancak bunu TypeScript'te kullanmaya çalıştığımda aldığım hatalar yukarıdakiler. var'ı let ile değiştirmeyi ve . eklemeyi denedim, başka öneriniz var mı? Teşekkürler.
dashboard.ts
var w = document.getElementById('wrapper');
var button = document.getElementById('randomize');
var image = w.children; // inner elements, your quotes divs
// a function to hide all divs
var hideDivs = function(divs) {
for (var div of divs) {
div.style.display = 'none';
}
}
hideDivs(image); // hide all initially
// on click
button.addEventListener('click', function(event) {
var rnd = Math.floor(Math.random() * image.length); // get random index
hideDivs(image); // hide all quotes
image[rnd].style.display = 'block'; // show random quote
event.target.textContent = 'Click one more time!'; // set button text. event.target is the button you've clicked
})
gösterge_paneli.html
<div id="wrapper">
<div class="image" img scr='../../assets/mood.jpg'></div>
<div class="image" img scr='../../assets/mood.jpg'></div>
<div class="image" img scr='../../assets/mood.jpg'></div>
<div class="image" img scr='../../assets/mood.jpg'></div>
<div class="image" img scr='../../assets/mood.jpg'></div>
</div>
<button id='randomize'>Next</button>
Cevap #1
Sorun, target'in EventTarget olarak yazılmış olması ve HTMLCollection olan image'in bir elemanının Element olarak yazılmış olmasıdır. Erişmek istediğiniz her iki özellik de HTMLElement üzerinde tanımlıdır. Yapabileceğiniz en basit şey, derleyiciye bu iki öğenin aslında sizin durumunuzda HTMLElement olduğunu söylemek için bir tür doğrulaması (type assertion) kullanmaktır.
// on click
button.addEventListener('click', function (event) {
var rnd = Math.floor(Math.random() * image.length); // get random index
hideDivs(image); // hide all quotes
(image[rnd] as HTMLElement).style.display = 'block'; // show random quote
(event.target as HTMLElement).textContent = 'Click one more time!'; // set button tqext. event.target is the button you've clicked
})
Ayrıca hideDivs kodunu doğru şekilde yazmak isteyebilirsiniz :
// a function to hide all divs
const hideDivs = function (divs : HTMLCollection) {
for (var div of divs) {
(div as HTMLElement).style.display = 'none';
}
}
